应用程序使用Android 10中的警报管理器终止后的本地通知

问题描述

我想显示特定时间的本地通知。这样我就可以使用警报管理器来设置特定时间的待定意图。但是在我的情况下,如果应用程序被用户杀死,则不会调用广播/服务。

检查下面的代码,帮助我解决为什么在应用程序被终止后仍未收到通知的情况。

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        

        Intent notifyIntent = new Intent(this,MyReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getbroadcast
                (MainActivity.this,1,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+30000,pendingIntent);
    }
}
public class MyReceiver extends broadcastReceiver {

    public MyReceiver() {
        
    }

    @Override
    public void onReceive(Context context,Intent intent) {
        
  
        Intent intent1 = new Intent(context,MyNewIntentService.class);
        context.startService(intent1);
    }
}
public class MyNewIntentService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        super.onStartCommand(intent,flags,startId);

        CommonUtil.showNotification(getApplicationContext());
        return START_STICKY;
    }
}

AndroidManifest.xml


 <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

  <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="false"
            />

        <service
            android:name=".MyNewIntentService"
            android:exported="false"
            />

解决方法

您可以在此处查看带有广播接收器的警报的工作示例。

How to use Android AlarmManager in Fragment in Kotlin?