【问题标题】:stopService doesn't stop's my service.... why?stopService 不会停止我的服务.... 为什么?
【发布时间】:2010-12-17 12:25:10
【问题描述】:

我的 android APP 上有一个后台服务,它正在获取我的 GPS 位置并将其发送到远程数据库。它工作正常。

问题是当我想停止服务时......它不会停止:S。 logcat 上也没有出现异常或错误......它根本不会停止。

这是启动我的服务的代码(带有按钮):

startService(new Intent(GPSLoc.this, MyService.class)); //enciendo el service

这是我停止它的代码(在 onactivityresult 方法上):

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

我已经调试了这个应用程序,并且我检查了每次调试它时都调用了 stopService 代码行,但它并没有停止......

我确信它没有停止,因为当我按下按钮停止服务时,我仍然从模拟器接收 gps 位置。

我做错了什么?

【问题讨论】:

  • 嘿,我有同样的问题,你能分享你的代码吗?

标签: android service


【解决方案1】:

你实现onDestroy()了吗?如果不是,我相信这可能是解决方案 - 你停止你的 Timer 或任何你用来在 onDestroy() 内运行服务的东西。

可以通过调用其 stopSelf() 方法或调用 Context.stopService() 来停止服务。

有关更多信息,请参阅此link

【讨论】:

  • 哦,我没有实现 ondestroy !!!!!!在服务上,我正在使用一个带有处理程序的线程和一个简单的处理程序。 ¿如何阻止他们??
  • 我不明白为什么要实现onDestroy()。它只是一个生命周期回调方法。你能澄清一下吗?
  • 我已经实现了onDestroy(),但是在stopService()之后没有调用它。 Fragment1 - context?.bindService(Intent(context, AudioService::class.java), serviceConnection, Context.BIND_AUTO_CREATE) context?.startService(Intent(context, AudioService::class.java).apply { putExtra(CONTENT_SELECTED_KEY, uri)}) Fragment2 - context?.stopService(Intent(context,AudioService::class.java).apply {putExtra(PLAYER_KEY, STOP.name)})
【解决方案2】:

我确信它没有停止,因为当我按下按钮停止服务时,我仍然从模拟器接收 gps 位置。

您可能没有取消注册您的LocationListener

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。我发现如果服务有GoogleApiClient 连接并且仍然获得位置更新,stopService() 完全没有效果,服务的行业()没有被调用。 为了解决这个问题,我在服务代码中创建了一个停止定位服务的函数。从活动中调用stopLocationService(),然后调用stopService。下面是代码示例:

    public class myLocationService extends Service{
    ...
    
        public void stopLocationUpdates() {
    
            LocationService.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);       
            mGoogleApiClient.disconnect();
    
        }
        ...
    } 
    

    在活动中,

    {
        ...
        if(mService != null && isBound) {
    
            mService.stopLocationUpdates();
            doUnbindService();
            stopService(new Intent(this,   myLocationService.class));
    
         }
         ...
    } 
    

    【讨论】:

      【解决方案4】:

      这种情况很常见,我需要在完成该过程之前停止我的服务。在某些情况下,使用 stopService(intent) 是不够的。您应该记住我的服务中的 onDestroy() 实现。示例:

      public class MyIntentService extends IntentService {
      
          // Defines and instantiates an object for handling status updates.
          private BroadcastNotifier mBroadcaster = null;
          private int progress = 0; //THIS IS MY COUNTER FOR EXAMPLE!!!
      
          public MyIntentService() {
              super("MyIntentService");
          }
      
          @Override
          protected void onHandleIntent(Intent intent) {
      
              progress = 0;
              int tiempo_disponible = intent.getIntExtra("minutos_disponible", 0);
      
              if (mBroadcaster == null){
      
                  mBroadcaster = new BroadcastNotifier(this);
              }
              // Broadcasts an Intent indicating that processing has started.
              mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);
      
              mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_RUNNING);
      
              while (progress < tiempo_disponible) {
      
                  progress++;
                  try {
                      Log.i(Constants.TAG, "Procesing " + progress);
                      mBroadcaster.notifyProgress(progress);
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
              // Reports that the feed retrieval is complete.
              mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
          }
      
          @Override
          public void onDestroy() {
              progress = 1000000; // WHITH THAT YOU FINISH THE CICLE IF tiempo_disponible NEVER IS MAYOR THAT 1000000, YOU CAN USE OTHER CONDITIONAL!!!!!!
              super.onDestroy();
          }
      } 
      

      这样,当您使用 stopService 方法停止服务时,您也将停止进程 o counter。

      public void stopService(){
              context.stopService(intent);
              LocalBroadcastManager.getInstance(context).unregisterReceiver(responseReceiver);
              responseReceiver = null;
              intent = null;
      }
      

      保重! @yaircarreno

      【讨论】:

      • 您使用了错误的服务类型。 IntentService 旨在管理其生命周期本身。一旦 onHandleIntent 方法的业务逻辑完成 - IntentService 就会自行销毁并释放所有相关资源。
      【解决方案5】:

      如果您正在跟踪 GPS 位置,您可能使用了GoogleApiClient

      这个概念是服务不会停止,

      如果GoogleApiClient 实例仍在其中连接。

      (或任何其他需要先销毁/注销的问题)

      因此,要使其正常工作,请在您的服务中实现 onDestroy()

      @Override
      public void onDestroy()
      {
          // Unregistered or disconnect what you need to
          // For example: mGoogleApiClient.disconnect();
          super.onDestroy();
      }
      

      【讨论】:

      • 我实际上是在尝试停止使用 google api 的服务,我忘记断开 api OnDestroy...!!案件结案..
      【解决方案6】:

      我发现停止服务的最佳方法是自行停止。这样您就可以确定它实际上会停止并保持数据完整性。如果您想从外部(活动)执行此操作,我通常使用全局静态属性。

      如果我有 MyServiceMyActivityMyObject,例如 (Kotlin)

      我的对象

      object MyObject{
          abort = false
      }
      

      我的服务

      override fun onHandleIntent(intent: Intent?) {
          startForeground(id,notification)   
          for (i in range){
              if (MyObject.abort) break
              // RUN SOME CODE HERE
          }
          stopForeground(true)
          stopSelf()
      }
      

      我的活动

      fun startService() {
          startForegroundService(Intent(this, OptimizationService::class.java))
      }
      fun stopService() {
          MyObject.abort = true
      }
      

      【讨论】:

        【解决方案7】:

        可能是您每次调用停止服务时都在创建一个新的 Intent。

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

        也许可以试试:

        Intent intnet = new Intent(GPSLoc.this, MyService.class); // create el service
        
        startService(intenet); 
        stopService(intent);
        

        【讨论】:

          【解决方案8】:

          对于那些想要定期向服务器发送请求的人,这是我的解决方案。你应该在你的 Activity 或 Fragment Activity 中有这个

          {
          private static final Long UPDATE_LOCATION_TIME  = 30 * 60 * 1000l; // 30 minute
          
          private AlarmManager alarm;
          private PendingIntent pIntent; 
          ...
          
          @Override
              protected void onResume() {
                  super.onResume();
          
                  // Run background service in order to update users location
                  startUserLocationService();
          
                  Log.e(TAG, "onResume");
              }
          
              @Override
              protected void onStop() {
                  super.onStop();
          
                  stopUserLocationService();
          
                  Log.e(TAG, "onStop");
              }
          
          private void startUserLocationService() {
                  Log.i(TAG, "Starting service...");
                  Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class);
                  pIntent = PendingIntent.getService(this, 0, intent, 0);
          
                  alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                  Calendar cal = Calendar.getInstance();
                  alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), UPDATE_LOCATION_TIME, pIntent);
              }
          
              private void stopUserLocationService() {
                  alarm.cancel(pIntent);
                  Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class);
                  stopService(intent);
              }
          
          }
          

          【讨论】:

            【解决方案9】:

            我的问题通过删除添加到 WindowManager ondestroy 的视图解决了

            public void onDestroy() {
                isRunning = false;
                super.onDestroy();
                if (checkBox!=null) {
                    windowManager.removeView(getlayoutparm(fabsetting,fabrateus,fabexit,true)); 
                    windowManager.removeView(checkBox); 
                }
             }
            

            【讨论】:

              【解决方案10】:

              在我的情况下,stopService 几乎同时与startService 一起调用,因此没有服务需要停止。尝试延迟stopService 几秒钟。 :)

              【讨论】:

                【解决方案11】:

                @Override

                public void onDestroy() {
                
                    Log.d(TAG, "onDestroy");
                    super.onDestroy();
                    if (mLocationManager != null) {
                
                        for (int i = 0; i < mLocationListeners.length; i++) {
                
                            try {
                
                                mLocationManager.removeUpdates(mLocationListeners[i]);
                
                            } catch (Exception ex) {
                
                                Log.d(TAG, "fail to remove location listners, ignore", ex);
                
                            }
                
                        }
                
                    }
                
                }
                

                【讨论】:

                • 在公共类 MyService extends Service 上试试这个
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-01-17
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多