0

我在服务中创建了一个大视图样式通知

我打算放一个按钮,将一些信息传递回活动,但似乎活动无法获得我之前设置的额外内容。

这是我用来显示通知的代码:

public class TestService extends Service {
...
@Override
public void onCreate() {
    showNotification();
}
private void showNotification() {
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
            new Intent(this, TestActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

    Intent discardIntent = new Intent(this, TestActivity.class);
    discardIntent.putExtra("piAction", "discard");
    PendingIntent piDiscard = PendingIntent.getActivity(this, 0, discardIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.drawable.ic_launcher);
    mBuilder.setContentTitle("Test Notification");
    mBuilder.addAction(R.drawable.content_discard, "Discard", piDiscard);
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText("Test service is running"));

    mBuilder.setContentIntent(contentIntent);
    Notification notification = mBuilder.build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(0, notification);
} 
...  

}

这是将捕获通知中按钮发送的信息的活动

public class TestActivity extends Activity {

...
@Override
protected void onResume() {
        super.onResume();
        Log.i("Activity Resume", "onResume");
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            Log.i(TAG, "extras not null");
            if (extras.containsKey("piAction")) {
                Log.i("Intent Received", "piAction");

            }
        }
}
...
}

请注意,启动时TestActivity,它也会启动TestService。我打算做的是,当discard点击通知内的按钮时,它会将先前放置的额外内容传递回TestActivity. 但是,经过几次测试,我发现TestActivity可以成功启动,但无法获得我之前设置的附加功能。

那么我的代码中可能存在的问题在哪里?

如果您需要任何其他详细信息,请在评论中说明,我会相应地用这些详细信息更新我的问题。

4

1 回答 1

0

当我将通知中的字符串传递给启动活动以解决该问题时,我遇到了相同类型的问题 1)现在在您的应用程序扩展类中获取一个字符串,例如公共字符串临时字段,而不是这个

discardIntent.putExtra("piAction", "discard");

用这个

YourApplication app = (YourApplication)getApplicationContext();
    app.temp = "discard";

在你的活动中而不是这个

 Bundle extras = getIntent().getExtras();
        if (extras != null) {
            Log.i(TAG, "extras not null");
            if (extras.containsKey("piAction")) {
                Log.i("Intent Received", "piAction");

            }
        }

从 YourApplication 获取您的 piAction 状态

YourApplication app = (YourApplication)getApplicationContext();
String stringFromNotification = app.temp;
于 2013-09-20T14:34:07.560 回答