Note that there are some explanatory texts on larger screens.

plurals
  1. POBroadcastReceiver - how to trigger service every time user ON/OFF screen
    text
    copied!<p><em>Hello</em></p> <p>I want to check whether my service is running or not, if service is running, do nothing.</p> <p>But if service is not running, restart the service.</p> <p>So I do something like this.</p> <p><code>In Manifest.xml</code></p> <pre><code>&lt;receiver android:name="com.varma.android.aws.receiver.Receiver"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.SCREEN_ON" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.SCREEN_OFF" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p><code>Receiver.java</code></p> <pre><code>public class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("aws", "Received..."); if(isMyServiceRunning(context)) { Log.v("aws", "Yeah, it's running, no need to restart service"); } else { Log.v("aws", "Not running, restarting service"); Intent intent1 = new Intent(context, Service.class); context.startService(intent1); } } private boolean isMyServiceRunning(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (Service.class.getName().equals(service.service.getClassName())) { return true; } } return false; } } </code></pre> <p><strong>But nothing is happening when I ON/OFF screen</strong></p> <p>What am I doing wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload