当主要活动被杀死时,在广播接收器中创建的通知消失

时间:2017-03-01 15:18:04

标签: android broadcastreceiver android-notifications

我正在听清单

中的电池低电量系统广播
    <receiver android:name=".BatteryLowReceiver"  android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_LOW"/>
        </intent-filter>
    </receiver>

然后在我的.BatteryLowReceiver我使用NotificationCompat.builder

创建通知
    @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());
}

发送低电量系统广播时,通知会正确显示。但是,如果我关闭了应用的主要活动,通知就不会继续存在。这是预期的行为吗?我会假设通知一直持续到用户解雇或点击它为止。

我认为它与上下文有关?我已尝试删除代码的AyncTask部分,但这没有帮助。我已根据另一个问题的建议将上下文作为成员变量。但没有运气。如何在用户解除通知之前收到通知?

0 个答案:

没有答案