运行 像 whatsapp 这样的后台服务

Running Service in Background like whatsapp

我不知道为什么这段代码不起作用,我正在尝试像 whatsapp 这样的后台服务,它会永远运行并检查通知。

但这不起作用,我不知道我哪里做错了。

  1. 我在 android 清单中添加了服务

<receiver android:name=".Notifications"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.TIMEZONE_CHANGED" /> <action android:name="android.intent.action.TIME_SET" /> <action android:name="com.application.Notifications" /> </intent-filter> </receiver> <service android:name=".BackgroundWorker"></service>

  1. 我创建了三个 classes "BackgroundWorker extends IntentService"

`public BackgroundWorker() { 超级("androidservice"); }

@Override
protected void onHandleIntent(Intent intent) {



    Log.v("BackgroundWorker:","working" );

    //user method
    createNotification(getApplicationContext(),"BackgroundWorker");
}`

2。 class'Notifications extends BroadcastReceiver'

@Override
public void onReceive(final Context context, Intent intent) {

    Log.d("BroadcastReceiver","onReceive");

    Intent t = new Intent(context,BackgroundWorker.class);
    context.startService(t);

}

3。我创建了第三个 class ` Long alertTime = new GregorianCalendar().getTimeInMillis() + 1*1000;

    Intent notifications = new Intent(this,Notifications.class);

    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,alertTime,1*1000,PendingIntent.getBroadcast(this,
            1,
            notifications,
            PendingIntent.FLAG_UPDATE_CURRENT));

    Log.d("AlarmManager",alarmManager.toString());`

我不知道我哪里做错了。

**虽然我已将重复设置为 1 秒,但我仍然会以 5 分钟的间隔收到通知**

并且我检查了android服务,我的应用程序不是运行 请帮帮我...

06-16 10:25:21.537 9833-9833/ D/BroadcastReceiver: onReceive 06-16 10:25:21.614 9833-12666/D/BroadcastReceiver: createNotification 06-16 10:30:21.245 9833-9833/ D/BroadcastReceiver: onReceive 06-16 10:30:21.376 9833-15746/r D/BroadcastReceiver: createNotification 06-16 10:35:21.209 9833-9833/ D/BroadcastReceiver: onReceive 06-16 10:35:21.283 9833-18645/ D/BroadcastReceiver: createNotification 06-16 10:40:21.179 9833-9833/ D/BroadcastReceiver: onReceive 06-16 10:40:21.224 9833-21479/ D/BroadcastReceiver: createNotification 06-16 10:45:21.188 9833-9833/ D/BroadcastReceiver: onReceive 06-16 10:45:21.246 9833-24302/ D/BroadcastReceiver: createNotification

IntentService 在 onHandleIntent() 中的代码执行后自行停止。您需要扩展一个普通的服务并自己处理线程。如果您不调用 stopSelf,该服务将继续 运行(可能直到系统终止它)。