带服务的广播接收器(发出通知)



如何向在特定持续时间后未使用应用程序的用户发送通知?因此,如果用户有5分钟没有打开应用程序,则会收到一条通知,邀请他们用短信打开应用程序。即使在重新启动手机后,此功能也应起作用。你能给我一些线索吗?

public class Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "broadcast", Toast.LENGTH_SHORT).show();
Intent i = new Intent(context.getApplicationContext(), NotificationService.class);
context.getApplicationContext().startService(i);
}
private void createNotification(Context context, String m, String t, String a) {
PendingIntent notificationIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class),0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1")
.setSmallIcon(R.drawable.icon)
.setContentTitle(m)
.setTicker(a)
.setContentText(t);
builder.setContentIntent(notificationIntent);
builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}

}

public class NotificationService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this, "Service", Toast.LENGTH_SHORT).show();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroy", Toast.LENGTH_LONG).show();
}}

清单在标签中

<receiver android:name=".model.Broadcast"  >
</receiver>
<service android:enabled="true" android:name=".model.NotificationService" />

所以广播没有开始,我不知道为什么。我想在应用程序未打开或未被积极使用时开始广播,广播必须在1或5分钟后启动服务以发送通知。

您的通知接收器不包含Broadcast receiver调用的任何Intent Filter。请检查IntentFilter。

<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>

不要将服务作为startService启动,它在Android O上崩溃,因为背景限制,请使用Job service来使用服务。

您可以从onReceive生成通知。