問題
ユーザーが押すSend "Button 1"と (下にスクロールしてアプリの構造を確認します)、 から新しいNotification
が作成されRefreshService
ます。ユーザーがこの通知を押すと、インスタンスが開始され、 の値をMainActivity
含む を受け取ります。String
Button 1
Intent
この値が表示されます。
ユーザーが今押すと、からSend "Button 2"新しいNotification
が作成されRefreshService
ます。ユーザーがこの通知を押すと、インスタンスが開始され、 の値を持つALSOMainActivity
を受け取ります。String
Button 1
Intent
ご想像のとおり、通常は value が存在するはずですButton 2
。
ユーザーが最初にボタンを押すSend "Button 2"と、常にButton 2
送信されます。
2 番目のボタンの値を取得する唯一の解決策は、電話機を再起動し、最初に 2 番目のボタンを押すことです。強制終了してもダメ。
別の方法で UI を変更できることもわかっています。しかし、「MainActivity」を別のアプリで再起動する必要があるアプリでは、このアプローチが必要なIntent
ので、アプローチは同じでなければなりません。
工事
と
Activity
呼ばれるMainActivity
と
IntentService
呼ばれるRefreshService
主な活動
public class MainActivity extends Activity implements View.OnClickListener {
public static final String RECEIVED = "received";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView)findViewById(R.id.textView_received)).setText(getIntent().getStringExtra(RECEIVED));
findViewById(R.id.button_1).setOnClickListener(this);
findViewById(R.id.button_2).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this, RefreshService.class);
if(v.getId() == R.id.button_1){
intent.putExtra(RECEIVED, "Button 1");
Toast.makeText(this,"Sent \"Button 1\"",Toast.LENGTH_LONG).show();
}
else if(v.getId() == R.id.button_2){
intent.putExtra(RECEIVED, "Button 2");
Toast.makeText(this,"Sent \"Button 2\"",Toast.LENGTH_LONG).show();
}
startService(intent);
}
}
RefreshService
public class RefreshService extends IntentService {
public RefreshService() {
super("RefreshService");
}
@Override
protected void onHandleIntent(Intent intent) {
String received = intent.getStringExtra(MainActivity.RECEIVED);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra(MainActivity.RECEIVED, received);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle("IntentServiceRefresh").setContentText(received).setSmallIcon(R.drawable.ic_notification_small).setContentIntent(pendingIntent);
Notification notification = builder.build();
// Hide the notification after it's selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
アプリのレイアウト