2012-05-29 3 views
0

Я использую locationListener с Gps. Когда мой символ Gps становится стабильным (т. Е. Перестает мигать) означает, что у него появилось новое местоположение, в это время он висит мое приложение на некоторое время. используя locationListener в Service.But, когда я запускаю приложение «Карты» (приложение google maps.apk), он работает плавно на Gps.so. В чем проблема с моим приложением, которое работает очень плавно, если Gps отключен.Gps, GeoCoding вызывает зависание приложения в android

Мой код здесь

public class LocationUpdateService extends Service implements IActionController{ 
    private LocationManager _locationManager; 
    private String   _provider; 
    private boolean   _gpsEnabled; 
    private boolean   _networkEnabled; 
    private String   _json; 
    private boolean  _locationSendingByCheckIn; 
    private Intent   _intent; 
    int i=1; 

    //private boolean  _locationAvailable; 


    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     i=1; 
     String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",getApplicationContext()); 
     if (tracking_key == null || tracking_key.equals("")||!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext())) 
     { 
      stopService(new Intent(getApplicationContext(),LocationUpdateService.class)); 
     } 
     else 
     { 
      _locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID); 
      getLocation(); 

     } 


    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 

     try { 
      if(!MySharedPreference.getBoolean(MySharedPreference.APP_ALLOWED_TO_POST_LOCATION, false, getApplicationContext())) 
      { 
       stopService(new Intent(getApplicationContext(),LocationUpdateService.class)); 
       return; 
      } 
      else if (intent.getExtras() != null) 
      { 


       if (intent.getExtras().getBoolean("locationSendingAlarm")) 
       { 
        _locationSendingByCheckIn=false; 

        _gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
        _networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
        String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext()); 

        if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER)&&_locationManager!=null&&!_gpsEnabled&&_networkEnabled) 
        { 
         _locationManager.removeUpdates(locationListener); 
         getLocation(); 
         sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS); 
        } 
        else if((_providerOld.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER))&&_gpsEnabled) 
        { 
         sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS); 
         if(_locationManager != null) _locationManager.removeUpdates(locationListener); 
         getLocation(); 
        } 
        else if(_providerOld.equalsIgnoreCase("")) 
        { 

         if(_locationManager != null) _locationManager.removeUpdates(locationListener); 
         getLocation(); 

        } 
        else 
        { 
         sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_SOS); 
        } 


       } 


       else if(intent.getExtras().getBoolean(AppConstants.APP_REPORT_TYPE_CHECK_IN)) 
       { 
        _intent=new Intent(AppConstants.CHECK_IN_BROADCAST_RECEIVER); 
        _locationSendingByCheckIn=true; 
        sendLocationOnServer(LocationUpdateService.this,AppConstants.APP_REPORT_TYPE_CHECK_IN); 

       } 
       else if(intent.getExtras().getBoolean(AppConstants.APP_SETTINGS_CHANGED)) 
       { 
        setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID); 
        if(_locationManager != null) _locationManager.removeUpdates(locationListener); 
        getLocation(); 
       } 
      } 
     } 
     catch (Exception e) { 
     } 

    } 



    private void getLocation() 
    { 

       try{ 

        _gpsEnabled=_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
        _networkEnabled=_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 


        /*if(!_gpsEnabled && !_networkEnabled) 
      { 

      }*/ 

        /*Criteria criteria = new Criteria(); 
      criteria.setAccuracy(Criteria.ACCURACY_FINE); 
      _provider = _locationManager.getBestProvider(criteria, false);*/ 


        /* Bundle bundle = new Bundle(); 
       // they would help boost my gps, 
       boolean xtraInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER, 
                 "force_xtra_injection",bundle); 
       boolean timeInjection=_locationManager.sendExtraCommand(LocationManager.GPS_PROVIDER, 
                 "force_time_injection",bundle);*/ 

        long timeInterval=getTimeInterval(); 
        try 
        { 
         if(timeInterval==1000*60) 
          timeInterval=1000*60*2-1000*20; //100 seconds 
         else if(timeInterval==1000*60*5) 
          timeInterval=1000*60*5-1000*30;// 4.5 minutes 
         else timeInterval=1000*60*5-1000*30; //4.5 minutes 
        } 
        catch (Exception e) { 
         timeInterval=1000*60*5-1000*30; //4.5 min 
        } 

        if(_gpsEnabled) 
        { 
         _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,timeInterval,200,locationListener); 
         return; 
        } 
        else if(_networkEnabled) 
        { 
         _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,timeInterval,200,locationListener); 
         return; 
        } 
        else 
        { 
         MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext()); 
        } 
        /*Location location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      if(null==location) 
      { 
       location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
      } 
      if(null==location) 
      { 
       location = _locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 

      } 
      else if(location != null && location.getProvider()!=null) 
      { 
       _locationManager.requestLocationUpdates(location.getProvider(),5*60*1000,0,locationListener); 
       _locationAvailable=true; 

      }*/ 


       } 
       catch(Exception ex) 
       { 
        MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", getApplicationContext()); 
       } 





    } 

    /** 
    * 
    * Location listener 
    */ 
    LocationListener locationListener = new LocationListener() { 
     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      /* 
       Toast.makeText(getApplicationContext(), "status changed", Toast.LENGTH_SHORT).show(); 
      switch (status) { 
      case LocationProvider.OUT_OF_SERVICE: 
       break; 
      case LocationProvider.TEMPORARILY_UNAVAILABLE: 
       break; 
      case LocationProvider.AVAILABLE: 
       break; 
      }*/ 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 




     } 

     @Override 
     public void onLocationChanged(final Location location) { 
      Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show(); 
      i++; 
      saveLocation(getApplicationContext(),location); 


     } 
    }; 
    public void saveLocation(Context context, Location location) 
    { 
     if(location!=null) 
     { 

      double _latitude=location.getLatitude(); 
      double _longitude=location.getLongitude(); 
      double _altidude=location.getAltitude(); 
      float _accuracy=location.getAccuracy(); 
      float _bearing=location.getBearing(); 
      float _speed=location.getSpeed() * 3.6f; 
      long _time=location.getTime(); 
      String _address=getAddress(location); 

      double _latitudeOld =MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context); 
      double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context); 


      MySharedPreference.putBoolean(MySharedPreference.IS_LOCATION_STATIC, _latitude == _latitudeOld && _longitude == _longitudeOld, context); 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, (float)_latitude, context); 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)_longitude, context); 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)_altidude, context); 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, _accuracy, context);;; 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, _bearing, context);; 
      MySharedPreference.putFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, _speed, context);; ; 
      MySharedPreference.putLong(MySharedPreference.PREVIOUS_LOCATION_TIME, _time, context); 
      MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, _address, context); 
      MySharedPreference.putString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, location.getProvider(), context); 


      if(NativeHelper.getDistanceInMeter(_latitude, _longitude, _latitudeOld, _longitudeOld) >= 330) 
      { 
       sendLocationOnServer(LocationUpdateService.this, AppConstants.APP_REPORT_TYPE_SOS); 
       setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID); 
      } 


     } 
    } 





    public void sendLocationOnServer(Context context, String reportType) 
    { 
     try{ 
      String tracking_key = MySharedPreference.getString(MySharedPreference.APP_TRACKING_KEY,"",context); 
      String _providerOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_PROVIDER, "", context); 
      if (tracking_key == null || tracking_key.equals("") ||_providerOld.equals("")) 
      { 
       return ; 
      } 

      double _latitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LATITUDE, 0.0f, context); 
      double _longitudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_LONGITUDE, (float)0.0, context); 
      double _altidudeOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ALTITUDE, (float)0.0, context); 
      float _accuracyOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_ACCURACY, (float)0.0, context);;; 
      float _bearingOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_BEARING, (float)0.0, context);; 
      float _speedOld=MySharedPreference.getFloat(MySharedPreference.PREVIOUS_LOCATION_SPEED, (float)0.0, context);; ; 

      boolean isStatic = MySharedPreference.getBoolean(MySharedPreference.IS_LOCATION_STATIC, false, context); 
      String _addressOld=MySharedPreference.getString(MySharedPreference.PREVIOUS_LOCATION_ADDRESS, "Address not available", context); 

      RequestAppLocationSending appLocationSending=new RequestAppLocationSending(); 
      appLocationSending.setImei(NativeHelper.getDeviceId(context)); 
      appLocationSending.setBattery((int)TrackMyDeviceUtils.getBatteryLevel(context)); 
      appLocationSending.setLatitude(_latitudeOld); 
      appLocationSending.setLongitude(_longitudeOld); 
      appLocationSending.setAltitude((int)_altidudeOld); 
      appLocationSending.setAccuracy(_accuracyOld); 
      appLocationSending.setCouse(_bearingOld); 
      appLocationSending.setSpeed(_speedOld); 
      appLocationSending.setTracking_key(tracking_key); 
      appLocationSending.setAddress(_addressOld); 
      appLocationSending.setDate(TrackMyDeviceUtils.getFormatedDateForLocationSending()); 
      appLocationSending.setReportType(reportType); 
      appLocationSending.setStatic(isStatic); 

      if(_providerOld.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) 
       appLocationSending.setData_source("G"); 
      else 
       appLocationSending.setData_source("N"); 




      _json= appLocationSending.toJson(); 

      LocationSendingController locationSendingController=new LocationSendingController((IActionController)context, EventType.APP_LOCATION_SENDING); 
      try { 
       locationSendingController.requestService(_json); 
      } catch (Exception e) { 

      } 

     } 
     catch (Exception e) { 
      e.printStackTrace(); 

     } 
    } 
    private String getAddress(Location location) 
    { 
     List<Address> addresses; 
     try{ 
      addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
      return findAddress(addresses); 


     } 
     catch (Exception e) { 
      try{ 
       addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
       return findAddress(addresses); 
      } 
      catch (Exception e1) { 
       return "Address not available"; 
      } 

     } 
     //return "Address not available"; 
    } 
    private String findAddress(List<Address> addresses) 
    { 
     String address="Address not available"; 
     if(addresses!=null) 
     { 

      for(int i=0;i<addresses.size();i++){ 
       Address addre=addresses.get(i); 


       String street=addre.getAddressLine(0); 
       if(null==street) 
        street=""; 

       String city=addre.getLocality(); 
       if(city==null) city=""; 
       /*if(city!=null) 
        MySharedPreference.putString(MySharedPreference.PREVIOUS_CITY_NAME, city, getApplicationContext()); 
       else 
        city=MySharedPreference.getString(MySharedPreference.PREVIOUS_CITY_NAME, "", getApplicationContext());*/ 

       String state=addre.getAdminArea(); 
       if(state==null) state=""; 
       /*if(state!=null) 
        MySharedPreference.putString(MySharedPreference.PREVIOUS_STATE_NAME, state, getApplicationContext()); 
       else 
        state=MySharedPreference.getString(MySharedPreference.PREVIOUS_STATE_NAME, "", getApplicationContext());*/ 

       String country=addre.getCountryName(); 
       if(country==null) country=""; 
       /*if(country!=null) 
        MySharedPreference.putString(MySharedPreference.PREVIOUS_COUNTRY_NAME, country, getApplicationContext()); 
       else 
        country=MySharedPreference.getString(MySharedPreference.PREVIOUS_COUNTRY_NAME, "", getApplicationContext());*/ 



       address=street+", "+city+", "+state+", "+country; 

      } 
      return address; 
     } 
     return address; 
    } 
    private void setLocationSendingAlarm(int alarmId) { 

     AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
     Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class); 
     intent.putExtra("locationSendingAlarm", true); 
     PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent,0); 
     try { 
      alarmManager.cancel(pendingIntent); 
     } catch (Exception e) { 

     } 
     long timeForAlarm=getTimeInterval(); 

     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent); 

    } 


    private void cancleAlarm(int alarmId) 
    { 
     AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
     Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class); 
     intent.putExtra("locationSendingAlarm", true); 
     PendingIntent pendingIntent; 
     pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID, intent, 0); 
     try { 
      alarmManager.cancel(pendingIntent); 
     } 
     catch (Exception e) { 
     } 

    } 
    @Override 
    public Activity getMyActivityReference() { 
     return null; 
    } 
    @Override 
    public void setScreenData(Object screenData, int event, long time) { 

     Message msg=new Message(); 
     msg.obj=screenData; 
     msg.arg1=event; 
     handler.sendMessage(msg); 

    } 

    protected Handler handler = new Handler() { 
     public void handleMessage(android.os.Message msg) { 
      updateUI(msg); 
     } 
    }; 


    public void updateUI(Message o) 
    { 
     try{ 

      if(o.obj instanceof MyError) { 
       switch(((MyError)o.obj).getErrorcode()) 
       { 
       case MyError.NETWORK_NOT_AVAILABLE: 
       { 
        if(_locationSendingByCheckIn) 
        { 
         _intent.putExtra("Response","Network not available"); 
         _intent.putExtra("LocationPostedSuccessfuly", false); 
         sendBroadcast(_intent); 
         _locationSendingByCheckIn=false; 

        } 

        break; 
       } 
       case MyError.EXCEPTION: 
       case MyError.UNDEFINED: 
       { 
        if(_locationSendingByCheckIn) 
        { 
         _intent.putExtra("Response","Server not responding. Please try later"); 
         _intent.putExtra("LocationPostedSuccessfuly", false); 
         sendBroadcast(_intent); 
         _locationSendingByCheckIn=false; 
        } 
       } 
       } 
      } 
      else if (o.obj instanceof ResponseAppLocationSending) { 
       ResponseAppLocationSending responseAppLocationSending=(ResponseAppLocationSending) o.obj; 
       if(responseAppLocationSending.getResponce().contains("saved")) 
       { 

        if(_locationSendingByCheckIn) 
        { 
         _intent.putExtra("Response","Check In Submitted"); 
         _intent.putExtra("LocationPostedSuccessfuly", true); 
         sendBroadcast(_intent); 
        } 
        //else setLocationSendingAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID); 

       } 
       else { 


        if(_locationSendingByCheckIn) 
        { 
         _intent.putExtra("Response","Server not responding. Please try later"); 
         _intent.putExtra("LocationPostedSuccessfuly", false); 
         sendBroadcast(_intent); 

        } 
       } 
      } 
     } 
     catch (Exception e) { 
      if(_locationSendingByCheckIn) 
      { 
       _intent.putExtra("Response","Server not responding. Please try later"); 
       _intent.putExtra("LocationPostedSuccessfuly", false); 
       sendBroadcast(_intent); 
       _locationSendingByCheckIn=false; 
      } 
     } 
     _locationSendingByCheckIn=false; 
    } 






    private long getTimeInterval() 
    { 
     try{ 
      String s=MySharedPreference.getString(MySharedPreference.APP_REPORTING_TIME, "10", getApplicationContext()); 
      int time = Integer.parseInt(s); 
      if(time<1) time=10; 

      return time*1000*60; 
     } 
     catch (Exception e) { 
      return 1000*60*10; //10 minutes 
     } 
    } 

    @Override 
    public void onDestroy() 
    { 
     if(_locationManager!=null) 
      _locationManager.removeUpdates(locationListener); 
     cancleAlarm(AppConstants.PENDING_INTENET_LOCATION_PROVIDER_ENABLE_ALARM_ID); 
     super.onDestroy(); 
    } 








} 
+2

Я не знаком с разработкой Android, но, скорее всего, ваша проблема будет решена, если вы выполните свою логику локализации в отдельном потоке. – npinti

+1

Загрузите код – Lucifer

+0

, пока не укажете свой код. он не сможет много помочь. также если вы публикуете, не публикуйте весь код. опубликовать специальный раздел кода, который, по вашему мнению, может быть подозрительным. только тогда мы сможем помочь вам лучше – Javanator

ответ

2

Finaly Я получил решение моей problem.I делает Geo часто, но не кодирования в другом thread.So я сделал это (ли Geo кодирования в новом Thread)

public void onLocationChanged(final Location location) { 

      new Thread(new Runnable(){ 
       public void run(){ 
        _address=getAddress(location); 
       } 
      }).start(); 

     } 
    }; 
    private String getAddress(Location location) 
    { 
     List<Address> addresses; 
     try{ 
      addresses = new Geocoder(this,Locale.getDefault()).getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
      return findAddress(addresses); 


     } 
     catch (Exception e) { 
      try{ 
       addresses= ReverseGeocode.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
       return findAddress(addresses); 
      } 
      catch (Exception e1) { 
       return "Address not available"; 
      } 

     } 
     //return "Address not available"; 
    } 
    private String findAddress(List<Address> addresses) 
    { 
     String address="Address not available"; 
     if(addresses!=null) 
     { 
      for(int i=0;i<addresses.size();i++){ 
       Address addre=addresses.get(i); 
       String street=addre.getAddressLine(0); 
       if(null==street) 
        street=""; 
       String city=addre.getLocality(); 
       if(city==null) city=""; 

       String state=addre.getAdminArea(); 
       if(state==null) state=""; 

       String country=addre.getCountryName(); 
       if(country==null) country=""; 

       address=street+", "+city+", "+state+", "+country; 
      } 
      return address; 
     } 
     return address; 
    } 
    }