Android 通知方法NotificationCompat-无错误-无通知

Android 通知方法NotificationCompat-无错误-无通知,android,notifications,Android,Notifications,我想得到一个简单的通知。我见过很多使用旧API方法的示例,但我想使用更新的方法。我从API资源中将这段代码放在一起,它运行时没有错误。但是,我没有看到任何通知。我有查看通知的最低要求,至少从我所阅读的内容来看,我相信是这样。这是我的密码: public class Login extends Activity { public static Context ctx; public void onCreate(Bundle savedInstanceState) { ctx =

我想得到一个简单的通知。我见过很多使用旧API方法的示例,但我想使用更新的方法。我从API资源中将这段代码放在一起,它运行时没有错误。但是,我没有看到任何通知。我有查看通知的最低要求,至少从我所阅读的内容来看,我相信是这样。这是我的密码:

public class Login extends Activity {
    public static Context ctx;

public void onCreate(Bundle savedInstanceState) {
    ctx = this;
 }

private static void notice(String msgfrom, String msg) {
    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(ctx);
    mBuilder.setSmallIcon(R.drawable.ic_launcher);
    mBuilder.setContentTitle("New message from " + msgfrom.toString());
    mBuilder.setContentText(msg);
    mBuilder.build();
}
}
感谢下面的帮助,我将代码修改为

NotificationCompat.Builder nb =   new NotificationCompat.Builder(ctx);
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setContentTitle("New message from " + msgfrom.toString());
nb.setContentText(msg);
nb.setAutoCancel(true);

Notification notification = nb.build();
NotificationManager NM = (NotificationManager)         
ctx.getSystemService(NOTIFICATION_SERVICE);
NM.notify(0, notification); 
试试这个

只需在
onCreate()中调用

试试这个

只需在
onCreate()中调用

如果要在所有Android设备中运行通知


如果您想在所有Android设备中运行通知,您将错过最后一步。您正在生成通知,但仍需要以以下方式将其发布到系统:

((NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE)).notify(100,mBuilder.build());

编辑:

notify方法中使用的整数100(我随机选择)是通知的唯一标识符。如果需要更新或取消通知,则应使用相同的标识符


注意:

将活动的联系人存储在静态变量中,可能会导致内存泄漏! 相反,您可以更改以下内容:

private static void notice(String msgfrom, String msg)
对此

private static void notice(Context ctx , String msgfrom, String msg)

然后删除静态变量。

您错过了最后一步。您正在生成通知,但仍需要以以下方式将其发布到系统:

((NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE)).notify(100,mBuilder.build());

编辑:

notify方法中使用的整数100(我随机选择)是通知的唯一标识符。如果需要更新或取消通知,则应使用相同的标识符


注意:

将活动的联系人存储在静态变量中,可能会导致内存泄漏! 相反,您可以更改以下内容:

private static void notice(String msgfrom, String msg)
对此

private static void notice(Context ctx , String msgfrom, String msg)

因此,请删除静态变量。

这不是使用NotificationCompative,这不是使用NotificationCompativeMOST。。非常感谢。我为我的情况缩短了密码,但是你的密码把我带到了那里!非常好。。非常感谢。我为我的情况缩短了密码,但是你的密码把我带到了那里!谢谢,是的,我从“Dhaval Sodha Parmar”的回答中得出了这个结论。这是一个学习曲线…至于你建议不要将我的活动存储在静态变量中。很好的建议-我会试试。谢谢,是的,我从“Dhaval Sodha Parmar”的回答中得到了这个建议。这是一个学习曲线…至于你建议不要将我的活动存储在静态变量中。好建议-我会试试的。