【问题标题】:Execute a method from notification从通知执行方法
【发布时间】:2014-09-16 05:00:08
【问题描述】:

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

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,没关系。但是我想在mainactivity中运行一个方法。

示例:你会看到setContentTextuser01 发送了一条消息,当用户按下通知我想在主活动中运行startChat(user01) 方法时,我该怎么做?

【问题讨论】:

  • 为什么不通过resultIntent.putExtra()将一些数据传递给Activity,然后通过getIntent()检查被调用Activity中的额外内容,然后根据调用Intent的数据进行导航?
  • 你能举个例子吗?
  • kevskree 下面的回答与我的建议一致

标签: android android-notifications


【解决方案1】:

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

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

然后,在您的 Activity(onCreateOnResume)中,您可以调用

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

【讨论】:

  • 可以放jsonobject吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多