【发布时间】:2021-09-01 21:32:32
【问题描述】:
场景: 当应用程序处于睡眠状态或在后台时,会向设备发送通知。用户单击通知并期望应用程序在后台显示当前活动的情况下打开。
到目前为止我尝试过的解决方案.. 在我的
NotificationLister extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
//I directy
Intent intent = new Intent(this, MyActivity.class);
//pass necessary extras here and flags
getApplication().startActivity(intent);
}
}
^ 以上工作正常,因为我已经知道当应用程序被带到前台时当前存在什么活动但是当我不完全知道存在什么活动时..(假设我们有主要使用的两个活动是 -- MyActivity 和 MyOtherActivity),现在这将不起作用,因为在 onResume() of MyOtherActivity 上,getIntent().getExtras() 将不包含自 @ 以来在我的 NotificationListener 服务类中设置的新附加内容987654327@ 已明确定义。
所以我从这个答案Android: How can I get the current foreground activity (from a service)? 中尝试了解决方案#4,以便我可以动态传递额外内容并重新打开所述当前活动。这让我想到了下面的问题。
问题:
Intent.ACTION_USER_FOREGROUND 受到此错误 Permission Denial: not allowed to send broadcast android.intent.action.USER_FOREGROUND 的限制
我看到了类似的解决方案,即在清单文件 <uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions"/> 中声明这一点,但这并不能真正解决我的问题,正在记录同样的问题。
在这种情况下我们可以使用什么合适的Intent.action?还是有其他合适的方法来处理这个问题?
Manifest.xml
<service android:name=".NotificationListener"/>
<receiver android:name=".MyBroadcastReceiver"/>
MyOtherActivity.java
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_FOREGROUND);
BroadcastReceiver mReceiver = new MyBroadcastReceiver();
registerReceiver(mReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
//I think it could also be okay to registerReceiver here
}
@Override
public void onDestroy() {
this.unregisterReceiver(broadcastReceiver);
super.onDestroy();
//on debug this is always called after sendBroadcast() and then the Permission Denial error
}
NotificationListener.class
NotificationLister extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.setAction(Intent.ACTION_USER_FOREGROUND);
broadcastIntent.putExtra("myNecessaryExtra", intent.getStringExtra("test"));
sendBroadcast(broadcastIntent);
}
}
MyBroadcastReceiver.class
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String responseString = intent.getStringExtra("myNecessaryExtra");
//on debug this doesn't get called because of the Permission Denial error
}
}
【问题讨论】:
标签: android android-activity notifications broadcastreceiver intentservice