I have a service that performs requests to the network at intervals of a minute. I was told to run it when I turn on the device. I did this. Now we need to make it work in standby mode and I can't understand anything, even the documentation. Everywhere they write about getting WakeLock and calling acquire , but they don’t write where to write it.
Once again: the service should start once both when the device is turned on and when the application is started. And if the device turns on and the user opens the application? Will start two services?
My BroadCastReceiver
public class BootReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Intent serviceIntent = new Intent(context, NotificationsService.class); startWakefulService(context, serviceIntent); } } } Service
public class NotificationsService extends IntentService { //блабла public NotificationsService(){ super("NotificationService"); } public void onCreate() { super.onCreate(); Log.d(LOG_TAG, "onCreate"); pref = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE); configEditor = pref.edit(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(LOG_TAG, "onStartCommand"); new Thread(){ @Override public void run() { connectWithIntervale(); } }.start(); return super.onStartCommand(intent, flags, startId); } public void connectWithIntervale(){ try { TimeUnit.MINUTES.sleep(1) } catch(Exception ignored) {} //запрос в сеть } @Override protected void onHandleIntent(Intent intent) { PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NotificationWL"); wakeLock.acquire(); BootReceiver.completeWakefulIntent(intent); } I start service from activity so
Intent i = new Intent(context, NotificationsService.class); startService(i); What else to do? Or is that all? I do not understand anything, the receiver will start the service when it is turned on, and then what will the activity do?