我正在尝试通过运行两个不同的活动来发出一个通知,其中有两个按钮可以执行两个不同的操作。通知及其按钮显示在通知栏上,但是按下任一按钮都无法启动指定的活动。
以下是代码:
private void addNotification() {
int requestID = (int) System.currentTimeMillis();
NotificationCompat.Builder builder = (android.support.v7.app.NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ibutton)
.setContentTitle("Timer running..")
.setContentText(timerString);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
//Add buttons to notification
//First make the intent
Intent pauseIntent = new Intent(this, pauseActivity.class);
//Wrap it in pending intent to trigger later
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
//Same again for stop button
Intent stopIntent = new Intent(this, stopActivity.class);
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, requestID, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.stop, "Stop", stopPendingIntent);
// Add as notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mNotificationId = 001;
notificationManager.notify(mNotificationId, builder.build());
}
编辑:我尝试启动的其中一项活动的示例:
public class stopActivity {
public stopActivity() {
MainActivity.stopped = true;
}
}
如果有更简单的方法可以简单地从通知栏中的按钮更改MainActivity中变量的值,那么我也很想听到,但据我所知,唯一的选择是启动一项新活动
答案 0 :(得分:0)
编辑:我尝试启动的其中一项活动的示例:
public class stopActivity {public stopActivity(){ MainActivity.stopped = true; }}
这不是Activity
。 Activity
extends Activity
!
这只是一个POJO课程,你无法按照你PendingIntent
的方式开始它。
只需使用Intent
MainActivity
{"额外"改变它的价值。这是一个例子:
Intent pauseIntent = new Intent(this, MainActivity.class);
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pauseIntent.putExtra("pause", true);
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
然后,在MainActivity.onNewIntent()
:
if (intent.hasExtra("pause")) {
this.paused = true; // whatever you want to do when "pause" is pressed
}