2016-08-19 1 views
1

나는 서비스 핸드 헬드 쪽의 위치를 ​​얻는 Android Wear 시계 얼굴을 개발했습니다. 여기에서 얻은 AsyncTask 코드를 사용합니다. 이 오류는 전화 배터리의 약 50 %를 소모합니다. 왜 그런지 모르겠습니다. 도와주세요. 오류 :서비스 내 위치를 가져올 때 죽은 스레드에서 처리기로 메시지 보내기

W/MessageQueue: Handler (android.location.LocationManager$ListenerTransport$1) {93795ca} sending message to a Handler on a dead thread 
                   java.lang.IllegalStateException: Handler (android.location.LocationManager$ListenerTransport$1) {93795ca} sending message to a Handler on a dead thread 
                    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543) 
                    at android.os.Handler.enqueueMessage(Handler.java:631) 
                    at android.os.Handler.sendMessageAtTime(Handler.java:600) 
                    at android.os.Handler.sendMessageDelayed(Handler.java:570) 
                    at android.os.Handler.sendMessage(Handler.java:507) 
                    at android.location.LocationManager$ListenerTransport.onLocationChanged(LocationManager.java:248) 
                    at android.location.ILocationListener$Stub.onTransact(ILocationListener.java:58) 
                    at android.os.Binder.execTransact(Binder.java:453) 

내 서비스 : 나는 새로운 개발자를하고있어이 문제를 해결하기 위해 노력하고 들어

private class Task extends AsyncTask 
    { 
     private String resp; 
     @Inject 
     IWeatherApi api; 

     @Override 
     protected Object doInBackground(Object[] params) 
     { 
      if (this.isCancelled()) { 
       return null; 
      } 
      try 
      { 
       Log.d(TAG, "Task Running"); 
       RoboGuice.getInjector(WeatherService.this.getApplicationContext()).injectMembers(this); 

       if (!mGoogleApiClient.isConnected()) 
       { mGoogleApiClient.connect(); 

       } 

       final DataMap config = new DataMap(); 

       WeatherInfo infoNetwork = api.getCurrentWeatherInfo(latitude, longitude); 

       config.putInt(KEY_WEATHER_TEMPERATURE, infoNetwork.getTemperature()); 
       config.putString(KEY_WEATHER_CONDITION, infoNetwork.getCondition()); 
       config.putLong(KEY_WEATHER_SUNSET, infoNetwork.getSunset()); 
       config.putLong(KEY_WEATHER_SUNRISE, infoNetwork.getSunrise()); 
       config.putInt(KEY_WEATHER_WIND_SPEED, infoNetwork.getSpeed()); 
       config.putInt(KEY_WEATHER_WIND_DEGREE, infoNetwork.getDeg()); 
       config.putInt(KEY_WEATHER_TEMP_MIN, infoNetwork.getTempMin()); 
       config.putInt(KEY_WEATHER_TEMP_MAX, infoNetwork.getTempMax()); 
       config.putInt(KEY_WEATHER_HUMIDITY, infoNetwork.getHumidity()); 
       config.putInt(KEY_WEATHER_PRESSURE, infoNetwork.getPressure()); 

        Wearable.MessageApi.sendMessage(mGoogleApiClient, mPeerId, PATH_WEATHER_INFO, config.toByteArray()) 
          .setResultCallback(
            new ResultCallback<MessageApi.SendMessageResult>() { 
             @Override 
             public void onResult(MessageApi.SendMessageResult sendMessageResult) { 
              Log.d(TAG, "SendUpdateMessage: " + sendMessageResult.getStatus()); 
              Log.v(TAG, KEY_WEATHER_CONDITION); 
              Log.v(TAG, "AsyncTask config in onResult: " + config.toString()); 
              Log.v(TAG, "mGoogleApiClient, mPeerId, PATH_WEATHER_INFO, config.toByteArray()" + mGoogleApiClient + " " + mPeerId + " " + PATH_WEATHER_INFO + " " + config); 
             } 
            } 
          ); 

      }catch (IllegalStateException e) { 
       e.printStackTrace(); 
       resp = e.getMessage(); 
      } 
      catch (Exception e) 
      { 
       Log.d(TAG, "Task Fail: " + e); 
      } 
      return null; 
     } 
    } 

이 도와주세요 : 여기

public class WeatherService extends WearableListenerService { 

private void startTask() { 

     Log.d(TAG, "Start Weather AsyncTask"); 
     mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build(); 

     mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = mLocationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = mLocationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     if (!isGPSEnabled && !isNetworkEnabled) { 
      Log.d(TAG, "no network provider is enabled"); 
      // no network provider is enabled 

     } else { 
      this.canGetLocation = true; 
      Log.d(TAG, "canGetLocation" + isGPSEnabled + isNetworkEnabled); 
      if (isNetworkEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         0, 
         0, new LocationListener() { 
          @Override 
          public void onLocationChanged(Location location) { 
           Log.d(TAG, "onLocationChanged: " + location); 
           //mLocation = location; 
           mLocationNetwork = location; 
           Task task = new Task(); 
           task.execute(); 
           Log.v(TAG, "isNetworkEnabled onLocationChanged: " + mLocationNetwork); 
           if (mLocationManager != null) { 
            mLocationManager.removeUpdates(this); 
           } 
          } 

          @Override 
          public void onStatusChanged(String provider, int status, Bundle extras) { 
           Log.d(TAG, "onLocationChanged: " + location); 
           if (mLocationManager != null) { 
            mLocationManager.removeUpdates(this); 
           } 
           //mLocation = location; 
           mLocationNetwork = location; 

          } 

          @Override 
          public void onProviderEnabled(String provider) { 
           if (mLocationManager != null) { 
            mLocationManager.removeUpdates(this); 
           } 

          } 

          @Override 
          public void onProviderDisabled(String provider) { 
           if (mLocationManager != null) { 
            mLocationManager.removeUpdates(this); 
           } 
          } 

         }); 
       Log.d("Network", "Network Enabled"); 
       if (mLocationManager != null) { 
        location = mLocationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
         Log.d(TAG, "Network Enabled: lat and long: " + latitude + longitude); 
         Task task = new Task(); 
         task.execute(); 
         Log.v(TAG, "isNetworkEnabled mLocationManager != null: " + location + latitude + longitude); 


        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        mLocationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          0, 
          0, new LocationListener(){ 
           @Override 
           public void onLocationChanged(Location location) 
           { 
            Log.d(TAG, "onLocationChanged: " + location); 

            //mLocation = location; 
            mLocationNetwork = location; 
            Task task = new Task(); 
            task.execute(); 
            Log.v(TAG, "isGPSEnabled onLocationChanged: " + mLocationNetwork); 
            if (mLocationManager != null) { 
             mLocationManager.removeUpdates(this); 
            } 
           } 

           @Override 
           public void onStatusChanged(String provider, int status, Bundle extras) 
           { 
            Log.d(TAG, "onLocationChanged: " + location); 
            //mLocation = location; 
            mLocationNetwork = location; 
            if (mLocationManager != null) { 
             mLocationManager.removeUpdates(this); 
            } 
           } 

           @Override 
           public void onProviderEnabled(String provider) 
           { 
            if (mLocationManager != null) { 
             mLocationManager.removeUpdates(this); 
            } 
           } 

           @Override 
           public void onProviderDisabled(String provider) 
           { 
            if (mLocationManager != null) { 
             mLocationManager.removeUpdates(this); 
            } 
           } 
          }); 
        Log.d("GPS", "GPS Enabled"); 
        if (mLocationManager != null) { 
         location = mLocationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
          Log.d(TAG, "GPS Enabled: lat and long: " + latitude + longitude); 
          Task task = new Task(); 
          task.execute(); 
          Log.v(TAG, "isGPSEnabled mLocationManager != null: " + location + latitude + longitude); 
         } 
        } 
       } 
      } 
     } 

    } 

그리고는 AsyncTask를하다 지금 아무 결과도없이.

+0

확실하지하지만 때문에 doBackground 내부 콜백 만약 내가 잘못 정정 해줘하지만, 시간에 의해 다시 아마 dobackground 호출에서 결과를 얻을 될 수 있습니다 여기에

당신이 당신의 문제를 해결하는 데 도움이 될 수있는 관련 SO 티켓입니다 죽은 –

+0

@ Rachit Solanki 그게 문제라면 어떻게 고칠 수 있니? 핸들러, 쓰레드, ASyncTask는 저에게 또 다른 세상과 같습니다. – Jack

+0

ResultCallback이 async 작업을 별도의 스레드에서 실행하는 경우 비동기 작업에서 제거 할 수 있습니다. –

답변

1

귀하의 오류 Handler on a dead thread은 서비스가 끝나면 즉시 죽을 수 있습니다. onHandleIntent 메서드를 호출 한 다음 onHandleIntent 메서드가 반환 되 자마자 스레드를 종료 할 때 IntentService을 사용하여 새 스레드를 만들 수 있습니다.

청취자를 다른 곳에서 만들려고 시도합니다. IntentService은 청취자가 사망하기 때문에 설정하기에 안전하지 않습니다. 주로 main thread 외부의 짧은 작업을 실행하는 데 사용됩니다. Sending message to a Handler on a dead thread when getting a location from an IntentService

관련 문제