Reputation: 1
i am learning how to deal with services..i created a small example. the mainActivity sends an integer to the service and the service uses that integer as the maximum iteration in a loop as shown below in the code.
the problem is when i call stopService(intent) i still receive value from the loop in the service class posted below..i think when i call stopService() the service will be destroyed
why that is hapenning?
service:
public class MyService extends Service {
private final String TAG = this.getClass().getSimpleName();
final static String MY_ACTION = "MY_ACTION";
@Override
public void onCreate() {
Log.w(TAG, "onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "onStartCommand");
int max = intent.getIntExtra("MAX", -1);
Log.v(TAG, "Act->Service : " + max);
MyThread myThread = new MyThread();
myThread.start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.w(TAG, "onBind");
return null;
}
class MyThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1500);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("value", i);
sendBroadcast(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
stopSelf();
}
}
}
Upvotes: 1
Views: 363
Reputation: 1006704
when i call stopService(intent) i still receive value from the loop in the service class posted below
Correct. That is because the thread is still running.
i think when i call stopService() the service will be destroyed
It is. That does not magically cause your thread to stop. You started the thread; you need to stop it, perhaps in onDestroy()
.
Upvotes: 1