当用户按发送“按钮1”(向下滚动以查看应用程序的构造)时,将从RefreshService
创建新的Notification
。如果用户按下此通知,MainActivity
实例就会启动,并在String
上收到值Button 1
的{{3}}。
显示此值。
当用户现在按下发送“按钮2”时,会从RefreshService
创建新的Intent
。如果用户按下此通知,MainActivity
实例就会启动,并在Notification
上收到值Button 1
的{{3}} ALSO 。
你可以猜测,通常应该有值Button 2
。
当用户按下的第一个按钮是发送“按钮2”时,将会发送所有Button 2
个。{/ p>
获取第二个按钮值的唯一方法是重新启动手机并先按第二个按钮。即使用力关闭也行不通。
我知道我也可以用另一种方式更改UI。但我需要在应用程序中使用此方法,我需要使用另一个String
重新启动'MainActivity',因此方法应该相同。
MainActivity
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);
}
}
应用布局
答案 0 :(得分:77)
我怀疑,因为Intent中唯一改变的是额外内容,PendingIntent.getActivity(...)
工厂方法只是将旧意图重新用作优化。
在RefreshService中,尝试:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
请参阅:
http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT