Reputation: 11
I have a simple service. My problem is that stopSelf()
does not work.
Here is my code:
public class MyService extends Service {
WindowManager.LayoutParams params;
LayoutInflater li;
@Override
public void onCreate() {
super.onCreate();
li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
700,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
final WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
final View view = li.inflate(R.layout.serviceeee, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyService.this.stopSelf();// doesnt work...
}
});
}
Upvotes: 1
Views: 1085
Reputation: 11
I tried this and now i can kill my service
@Override
public void onDestroy(){
windowManager.removeView(view);
super.onDestroy();
}
Upvotes: 0
Reputation: 3873
A service must be stopped itself by calling stopSelf() method, once it is finishes execution. However, you can also stop a service yourself by calling stopService() method.
stopService(new Intent(YourActivity.this, MyService.class));
For stopself():
It should be called when automatically by self, like service is going to finish the work then it's called something like below, which will use this method after some time.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//Your logic that service will perform will be placed here
//In this example we are just looping and waits for 1000 milliseconds in each loop.
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
For more, check this link which will suits your problem:- How to stop service by itself?
Upvotes: 3