我試圖在使用廣播接收器和計時器顯示的間隔中顯示通知。它在應用程序運行時工作,但在應用程序被終止時無法工作。Android廣播接收器在應用程序中斷時不工作
接收機看起來像
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>
它應用程序正在運行時的間隔中僅顯示通知。它在應用程序被殺時不顯示通知。我錯過了什麼?
也許您需要添加WAKE_LOCK權限? –
請更具體地說明「當應用程序被殺時」的含義。 – Karakuri
從後臺關閉應用程序。通知未收到 –