触发我的应用通知时执行某些操作

时间:2015-04-09 13:45:13

标签: android

我希望我的应用程序的某项活动能够在收到特定通知时收听并执行某些操作。

通知是从应用内部触发的。我对Android开发(以及一般的开发)都不熟悉,所以这里有一些我想做的伪代码:

Activity{
   notificationListener(){
      if(notification is received){
         //Do something
      }
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

检查Notification的{​​{3}}后,似乎无法收听发送Notification的信息。在深入思考之后,你会明白为什么我们不能。 AFAYK,我们编写代码来发送Notification而不是系统,对吧?我们肯定知道什么时候发送Notification,对吧?因此,如果您想知道何时发送Notification,为什么不做某事,例如发送BroadcastReceiver或启动Service以便注意其他代码?这一切都取决于我们的代码编写者。以下是如何自定义通知:

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.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);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());