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

时间:2018-07-09 11:40:00

标签: java android android-broadcastreceiver

如何在特定持续时间后向未使用该应用程序的用户发送通知?因此,如果该人未打开应用程序(例如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分钟后发送通知。

1 个答案:

答案 0 :(得分:0)

您的通知接收者不包含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及以后以Background Limitations的身份崩溃,请使用Job Service来使用服务。

您可以通过onReceive生成通知。