Java – The thread does not stop when stopService() is called in MainActivity

The thread does not stop when stopService() is called in MainActivity… here is a solution to the problem.

The thread does not stop when stopService() is called in MainActivity

Primary activity

public class MainActivity extends ActionBarActivity {

Context c=this;
Intent i;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b=(Button)findViewById(R.id.button1);
    Button b1=(Button)findViewById(R.id.button2);

b.setOnClickListener(new OnClickListener() {

public void onClick(View v)
        {
        i=new Intent(c,serv.class);
        startService(i);
        }
    });

b1.setOnClickListener(new OnClickListener()
    {

public void onClick(View v) {

stopService(i);

}
    });
}
}

Service

class bob implements Runnable{
Thread ac;

public void run() 
{
    while(true)
    {
        Log.d("tag","RUNNING");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
             TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}   }
public class serv extends Service {
Thread ac;

public void onCreate() {
        Log.d("tag","CREATED");
        super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("tag","SERVICE STARTED");

ac=new Thread(new bob());
    ac.start();

return Service.START_NOT_STICKY;

}

@Override
public void onDestroy() {
    Log.d("tag","DESTROYED");
try{
    ac.stop();
}catch(Exception e)
{e.printStackTrace(); }

}

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

}

When I click the StopService button, the ondestroy() message is invoked, but my thread continues to run.
The logs are as follows:

03-26 16:48:45.065: D/tag(15674): CREATED

03-26 16:48:45.065: D/tag(15674): SERVICE STARTED

03-26 16:48:45.065: D/tag(15674): RUNNING

03-26 16:48:45.495: D/tag(15674): RUNNING

03-26 16:48:46.065: D/tag(15674): RUNNING

03-26 16:48:46.495: D/tag(15674): RUNNING

03-26 16:48:47.065: D/tag(15674): RUNNING

03-26 16:48:47.495: D/tag(15674): RUNNING

03-26 16:48:48.065: D/tag(15674): RUNNING

03-26 16:48:48.505: D/tag(15674): RUNNING

03-26 16:48:48.615: D/tag(15674): DESTROYED

03-26 16:48:49.065: D/tag(15674): RUNNING

03-26 16:48:49.495: D/tag(15674): RUNNING

Solution

Try this…

class bob implements Runnable{
Thread ac;
boolean isRunning = true;
public void run() 
{
    while(isRunning)
    {
        Log.d("tag","RUNNING");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
             TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

} 
 public void stopRunning()
{
isRunning = false;
 }

And reference the runnable object in your service and call the stopRunning() method….

Related Problems and Solutions