Getting The Current Status Of Process/service Anytime The Activity Starts
Solution 1:
You just need to call the method which will check the status of the service in onResume mthod of your activity like this.
private boolean checkServiceStatus() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (ServiceName.class.getName().equals(service.service.getClassName())) {
returntrue;
}
}
returnfalse;
}
In onResume
@OverrideprotectedvoidonResume() {
super.onResume();
boolean serviceStarted= checkServiceStatus();
if (serviceStarted) {
mSvcButton.setText("Service Running");
} else {
mSvcButton.setText("Service not Running ... Click to Start");
}
}
Solution 2:
Your problem: but when I got out of activity [onBackPressed();], and then came back in [onCreate()]. This resets everything in your activity to default.
Answer : You can as well set a Flag in your service class and check the flag on the onResume or onCreate method of your activity class. For example:
publicclassHelloServiceextendsService {
publicstaticbooleanisRunning=false;
/** Called when the service is being created. */@OverridepublicvoidonCreate() {
this.isRunning = true;
}
/** The service is starting, due to a call to startService() */@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Overridepublic IBinder onBind(Intent intent) {
returnnull;
}
/** Called when The service is no longer used and is being destroyed *//* This method is not guaranteed to be called when android kill this service*/@OverridepublicvoidonDestroy() {
this.isRunning = false;
}
}
Then in your activity, you can do the following:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(HelloService.isRunning){ //this will also return false even when android kills your service
myButton.setText("Stop Service");
}
else{
myButton.setText("Start Service");
}
}
This approach is faster than iterating through list of running services on android os, In case your user's phone is running lots of services.
As for the BroadcastReceiver, you need to have a class that extends BroadcastReceiver and implement the onReceive method of the class. For example:
publicclassMyReceiverextendsBroadcastReceiver{
@OverridepublicvoidonReceive(Context context, Intent intent) {
//do work here
}
}
Now you can set your receiver to the instance of this class:
mReceiver.setReceiver(newMyReceiver());
Post a Comment for "Getting The Current Status Of Process/service Anytime The Activity Starts"