在 android 中使用闹钟添加通知

Adding notification using alarm in android

我有两个活动。在第一个 activity 中,我设置了闹钟。现在,我想在 5 秒后触发并开始第二个 activity。第二个 activity 推送通知。为此,我写了以下代码:

添加闹钟Class:

public class NotificationClass extends ActionBarActivity
{
    AlarmManager am;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_class);
        am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent in = new Intent(this,PushNotification.class);
        //b. create pending intent
        PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(),0,in,0);

        //c. set alarm for 5 seconds.
        am.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 5000,pi);
    }


}

添加通知的class:

public class PushNotification extends ActionBarActivity
{
    int notificationID = 11037;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_notification);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContentTitle("Notification Alert, Click Me!");
        mBuilder.setContentText("Hi, This is Android Notification Detail!");

        Intent resultIntent = new Intent(this, NotificationClass.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(NotificationClass.class);

// Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder.setAutoCancel(true);
// notificationID allows you to update the notification later on.
        mNotificationManager.notify(notificationID, mBuilder.build());
    }

}

但是,我没有得到想要的结果。我想我有一些问题需要报警 class。请帮我解决这个问题。我在 android 清单文件中需要什么?

您需要继承 BroadcastReceiver 并在清单文件中静态注册或通过 LocalBroadcastManager 使用 registerReceiver 动态注册。您的 BroadcastReceiver 的 onReceive() 方法将在收到警报生成的意图时推送通知。

静态注册很简单:

<receiver android:name=".MyAlarmReceiver" />

然后将通知代码从 PushNotification.onCreate() 方法移动到 MyAlarmReceiver.onReceive() 方法。

参见BroadcastReceiver or BroadcastReceiver tutorial

希望对您有所帮助。