2

Hello

I want to check whether my service is running or not, if service is running, do nothing.

But if service is not running, restart the service.

So I do something like this.

In Manifest.xml

<receiver android:name="com.varma.android.aws.receiver.Receiver">
<intent-filter>
    <action android:name="android.intent.action.SCREEN_ON" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.SCREEN_OFF" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

Receiver.java

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;
}

}

But nothing is happening when I ON/OFF screen

What am I doing wrong?

Mr.Sandy
  • 4,299
  • 3
  • 31
  • 54
Harsh Vakharia
  • 2,104
  • 1
  • 23
  • 26

2 Answers2

2

You can't register screen on/off broadcast through manifest file,tt doesn't work(need to explore why). Register it in your main activity through code

    ifilter=new IntentFilter();
    ifilter.addAction(Intent.ACTION_SCREEN_OFF);
    ifilter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(new Receiver(), ifilter);

Till the time your activity remains in memory you will receive these broadcasts in your receiver, i have tested it and able to receive broadcasts. However if your activity gets finished you won't receive these broadcasts. So registerting these broadcasts in some LocalService in your app with START_STICKY feature will solve your issue.

Akhil
  • 6,667
  • 4
  • 31
  • 61
1

If you want your service to stay up, you don't need to do this. Just have onStartCommand return START_STICKY. This will cause Android to restart any service it stops as soon as it has sufficient memory.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127