I'm a student new to android, and I have an application which use background service. I want to start/stop the service by clicking on a button, i'm doing it like this:
case R.id.enablepop:
if (!(pop.runningFlag))
startService(new Intent(mainScreen,PopUpService.class));
return true;
case R.id.disablepop:
if (pop.runningFlag)
stopService(new Intent(mainScreen,PopUpService.class开发者_开发问答));
return true;
In the onStart() function of the service I have runningFlag which I set to "true", then I create a thread that works while runningFlag is true. I set the runningFlag to false on onDestroy().
The problem is that the service won't stop. Can someone help me plz?
Try to use Handler, like here you can use Handler like Thread.
here is the example
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service{
private Handler handler;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
handler.post(updateStatus);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updateStatus);
handler = null;
}
@Override
public boolean onUnbind(Intent intent) {
handler.removeCallbacks(updateStatus);
handler = null;
return super.onUnbind(intent);
}
private Runnable updateStatus = new Runnable() {
@Override
public void run() {
// do something here
handler.postDelayed(updateStatus, 1000);
}
};
}
here the handler can was initialized into the oncreate method now after that when onStart method invoked then the updateStatus object will invoked through the handler.post() which will start the run method of this Runnable object.
Now in this, this will invoked the run() at once and execute the statement at once only so for repeating this task call inside this method on specific delay time like here 1000 milliseconds so after complete all the execution it will again call after 1 sec and repeating this task this will continue until you cannot remove the runnable object from the handler, so basically that was call into the onDestroy()
精彩评论