Android : Android - how to stop background service?

on Friday, March 27, 2015


I am beginner in Android development and now learning services. I have created a simple service to toast a string continuously. I took two buttons to start and stop service. When I am clicking on start button, the service is started and It is toasting string continuously. But when I go to stop service by clicking on stop button then it is not getting stopped. It is still toasting a string continuously. Thanks.



public class MyService extends Service {

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

doToast();

return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}


public void doToast()
{
final Handler handler= new Handler();
handler.postDelayed(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MyService.this, "hi", 0).show();
handler.postDelayed(this, 3000);
}

}, 3000);

}

}


This is code to start and stop service



startservice.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
});
stopservice.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
});

0 comments:

Post a Comment