您可以尝试在 BroadcastReceiver
中接收点击事件,然后从那里打开活动。
- 尝试使用以下方法向通知添加操作按钮:
timerNotificationBuilder.addAction(createNotificationActionButton("STOP");
createNotificationActionButton
方法在哪里:
public NotificationCompat.Action createNotificationActionButton(String text){
Intent intent = new Intent(this, StopwatchNotificationActionReceiver.class);
@SuppressLint("InlinedApi") PendingIntent pendingIntent = PendingIntent.getBroadcast(this, new Random().nextInt(100), intent, PendingIntent.FLAG_IMMUTABLE);
return new NotificationCompat.Action(0, text, pendingIntent);
}
- 创建一个名为
StopwatchNotificationActionReceiver
的类,并使其扩展 BroadcastReceiver
。以下是该类的代码:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class StopwatchNotificationActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PrefUtil.setIsRunningInBackground(context, false);
PrefUtil.setTimerSecondsPassed(context, 0);
PrefUtil.setWasTimerRunning(context, false);
context.stopService(MainActivity.serviceIntent);
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActvity(activityIntent);
}
}
同时,您需要在清单文件中注册该接收器,如下所示:
<receiver android:name="StopwatchNotificationActionReceiver"/>
- 其中
MainActivity.serviceIntent
是一个公共静态变量,看起来像这样:
public static Intent serviceIntent;
而这个意图仅用于像这样启动服务:
serviceIntent = new Intent(this, TimerService.class);
PrefUtil.setTimerSecondsPassed(this,seconds);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
}
或者你可以尝试简单的方法:
if (action != null && action.equals(ACTION_STOP_SERVICE)) {
Context context = this;
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActvity(activityIntent);
killService();
}
编辑
另一个解决方案在这里。你需要参考我的repo,因为我已经修改了文件以完成你的任务。在服务类中,参考this方法。在那里,如果动作是重置(r),我就启动活动。否则,它会打开广播接收器。然后,在活动中,我在onResume()
方法中接收额外的内容。如果没有点击重置按钮,它会打开接收器类。
一如既往地,您可以从这里查看应用程序的结果。
希望这段代码能够完成您的工作。
Intent.FLAG_IMMUTABLE
吗? - Sambhav Khandelwalthis
是Service
的上下文,我也尝试使用getAppContext()
和getBaseContext()
,但都没有成功。 - Nitzan Daloomy