MainActivity
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);
}
});
}
}
Serv
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 on the button to StopService, the ondestroy() message is called but my thread keeps on running. Log is given below:
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