[英]Android Broadcast Receiver not working when the app is killed
我試圖在一個間隔中使用廣播接收器和計時器顯示通知。 它在應用程序運行時有效,但在應用程序被殺死時無效。
接收器看起來像
public class MyReceiver extends BroadcastReceiver {
int j;
public void onReceive(final Context context, Intent intent) {
// Vibrate the mobile phone
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.schedule(new TimerTask() {
@Override
public void run() {
Log.d("ME", "Notification started");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ddc);
mBuilder.setContentTitle("My notification");
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setContentText("Hello World!");
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(j++, mBuilder.build());
}
},
0,
30000);
}
}
AndroidManifest.xml看起來像
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.background.pushnotification">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.background.myreceiver" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
它僅在應用程序運行時顯示間隔中的通知。 應用程序被殺時,它不會顯示通知。 我錯過了什么?
“當應用被殺時”並不是一個准確的陳述。 我猜你的意思是“當你從概覽屏幕(也就是最近任務列表)中移除你的應用程序時”。
一旦onReceive()
返回,如果您沒有活動在前台並且您沒有正在運行的服務,您的流程重要性將降至文檔所稱的“緩存流程”。 您的流程有資格隨時終止。 一旦您的進程終止,您的Timer
就會消失。 因此,您編寫的代碼將不可靠,因為您的進程可能會在30秒的窗口內終止。
其他可能性包括:
您正在為“應用程序被殺”時執行其他操作,其行為類似於“強制停止”,在“設置”中的應用程序屏幕上執行此操作。 通常,“強制停止”按鈕是強制停止應用程序的唯一方法,但偶爾設備制造商會做一些愚蠢的事情並強制停止從其他事情發生的事情(例如,設備提供的“應用程序管理器”)。 一旦您的應用程序被強制停止,您的代碼將永遠不會再次運行,直到用戶從主屏幕啟動器圖標啟動您的應用程序或設備上的其他內容使用顯式的Intent
啟動您的某個組件。
如果設備處於睡眠狀態,則在設備再次喚醒之前不會調用Timer
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.