Android 当主活动被终止时,在广播接收器中创建的通知将消失
我正在收听舱单中的电池电量不足系统广播Android 当主活动被终止时,在广播接收器中创建的通知将消失,android,broadcastreceiver,android-notifications,Android,Broadcastreceiver,Android Notifications,我正在收听舱单中的电池电量不足系统广播 <receiver android:name=".BatteryLowReceiver" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BATTERY_LOW"/> </intent-filter> </re
<receiver android:name=".BatteryLowReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
</intent-filter>
</receiver>
发送电池电量不足系统广播时,通知正确显示。但是,如果我关闭应用程序的主要活动,通知将不会持续。这是预期的行为吗?我假设通知会一直保留,直到用户解除或单击它
我相信这和背景有关?我已尝试删除代码中的
AyncTask
部分,但没有帮助。根据另一个问题的建议,我将上下文作为类的成员变量。但是没有运气。如何让通知一直保留到用户解除它 setAutoCancel(false)应该有帮助you@an_droid_devautoCancel只是让通知在单击时清除。当活动被取消时不会。我还是试过了,但通知还是不见了。谢谢。setAutoCancel(false)应该会有帮助you@an_droid_devautoCancel只是让通知在单击时清除。当活动被取消时不会。我还是试过了,但通知还是不见了。谢谢你。
@Override
public void onReceive(final Context context, final Intent intent) {
final PendingResult pendingResult = goAsync();
AsyncTask<String, Integer, String> asyncTask = new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
// Check for permissions
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
// Do stuff
// Show notification
showNotification(context, list.size());
// Must call finish() so the BroadcastReceiver can be recycled.
pendingResult.finish();
} else {
// TODO: failed because of permissions
pendingResult.finish();
}
return "";
}
};
asyncTask.execute();
}
void showNotification(Context context, int numberSent) {
// Get pending intent
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set notification properties
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_notif)
.setContentTitle(context.getString(R.string.notif_title))
.setContentText(context.getString(R.string.notif_text))
.setAutoCancel(true)
.setContentIntent(resultPendingIntent);
// Display notification
// TODO: Figure out why notif. goes away when the app is killed
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notifyMgr.notify(NOTIF_ID, builder.build());
}