我有一个简单的服务。我的问题是stopSelf()不起作用。

这是我的代码:

   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...
                }
            });
        }

最佳答案

完成服务后,必须通过调用stopSelf()方法来停止服务本身。但是,您也可以通过调用stopService()方法来自己停止服务。

stopService(new Intent(YourActivity.this, MyService.class));


对于stopself():

当服务自动完成时,应自动调用它,例如服务将要完成工作,然后将其称为如下所示,它将在一段时间后使用此方法。

  @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;
    }


有关更多信息,请检查此链接是否适合您的问题:-
How to stop service by itself?

关于android - 使用onClickListener停止Service内部的服务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33722801/

10-12 05:01