我在服务中创建了一个大视图样式通知
我打算放一个按钮,将一些信息传回活动,但似乎活动无法获得我之前设置的额外内容。
以下是我用来显示通知的代码:
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
可以成功启动,但它无法获得我之前设置的额外内容。
那么我的代码中可能出现的问题在哪里?
如果您需要任何其他详细信息,请在评论中说明,我会相应地更新我的问题。
答案 0 :(得分:0)
当我将通知中的字符串传递给我的启动活动以解决问题时,我遇到了同样的问题 1)拿一个字符串,例如应用程序扩展类中的public String temp字段 现在而不是这个
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;