从通知中执行方法

时间:2014-09-15 20:12:07

标签: android android-notifications

我有一个应用程序,我正在使用此代码发送通知

private void notBuild() {
    int mId=1;
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setContentTitle("Message")
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.twitter)
            .setContentText("user01 sent a message")
            .setNumber(15);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, MainActivity.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(MainActivity.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());
}

这是启动mainactivity并且没关系。但我想在主要活动中运行一个方法。

示例:当用户按下我要在主要活动中运行setContentText方法的通知时,您会在user01 startChat(user01)中看到发送消息。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以将数据放入resultIntent变量。

resultIntent.putExtra('key', 'useridhere');

然后,在您的活动(onCreateOnResume)中,您可以致电

String userId = getIntent().getStringExtra('key', null);
if(userId != null) 
{ 
   //StartChat(....);
}