【问题标题】:Stopping the services started by pending intent停止由未决意图启动的服务
【发布时间】:2014-04-25 06:15:35
【问题描述】:

我正在使用位置服务来获取位置更新。

我正在通过传递如下所示的待处理意图来启动服务

    btnStart.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (!isMyServiceRunning()) {
                mIntentService = new Intent(StartOrStopService.this,
                        LocationServices.class);
                mPendingIntent = PendingIntent.getService( 
                        StartOrStopService.this, 1, mIntentService, 0);

                locationrequest = LocationRequest.create();
                locationrequest.setInterval(1000*60);
                locationClient.requestLocationUpdates(locationrequest,
                        mPendingIntent);
                Toast.makeText(StartOrStopService.this, "Starting Service",
                        Toast.LENGTH_LONG).show();

            } else
                Toast.makeText(StartOrStopService.this,
                        "Service already running", Toast.LENGTH_LONG)
                        .show();

        }
    });

上面的代码运行良好,只需单击一个按钮即可启动服务。

我还有一个按钮,我用它来停止服务,由待定意图开始,下面是我尝试过的

   btnStop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (isMyServiceRunning()) {
                StartOrStopService.this.stopService(new Intent(StartOrStopService.this,
                        LocationServices.class));
                Toast.makeText(StartOrStopService.this,
                        "Stopping service",
                        Toast.LENGTH_LONG).show();
                System.out.println("Stop service");

            } else {
                Toast.makeText(StartOrStopService.this,
                        "No Services are running presently",
                        Toast.LENGTH_LONG).show();
            }

        }
    });

但我无法停止服务。有人可以建议我我在做什么错误。也给我一些建议??..

提前致谢:)

【问题讨论】:

标签: android service android-pendingintent


【解决方案1】:

我假设您并不是要停止服务。我假设您的意思是您想停止让位置客户端启动您的服务。为此,您只需调用 removeLocationUpdates() 并传递您在开始请求位置更新时使用的 PendingIntent

    mIntentService = new Intent(StartOrStopService.this, LocationServices.class);
    mPendingIntent = PendingIntent.getService(StartOrStopService.this, 1,
                                  mIntentService, 0);

    locationClient.removeLocationUpdates(mPendingIntent);

【讨论】:

    【解决方案2】:

    唯一的方法是服务被设计为通过意图命令停止。所以,你应该修改你的 LocationServices 类来处理这样的“特殊意图”。

    【讨论】:

    • 你能解释一下怎么做吗?谢谢:)
    • 您的服务应该覆盖 onCreate(或 IntentService 的 onStartCommand),如果 Intent 的附加部分中存在特殊参数,则它会停止。
    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多