2017-06-02 3 views
-2

J'utilise ici lieu de mettre à jour longitude et la latitude à chaque fois que je tente d'appuyer sur le bouton de retour ou de l'application de fond ou de toute instance, je veux le location_thread être arrêté en exécuter. Reprendre quand je passe à l'activité en cours.comment arrêter fil dans onBackPressed ou OnPause ou onResume

location_thread = new Thread() { 

      @Override 
      public void run() { 
       try { 
        while (!isInterrupted()) { 
         Thread.sleep(2000); 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           Log.i("TAG",currentThread().getName()+" Running"); 
           updateLatLongInfo(); 
          } 
         }); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }; 
     location_thread.setDaemon(false); 
     location_thread.start(); 
    } 

    @Override 
//whenever user press a backbutton thread must stoppped 
    public void onBackPressed() { 
     super.onBackPressed(); 
     location_thread.stop(); 
     Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class); 
     startActivity(intent); 
     finish(); 
    } 


    private void updateLatLongInfo() { 
     try { 
      int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); 
      latlongInfo.setBackgroundResource(R.drawable.latlng_info); 
      GradientDrawable drawable = (GradientDrawable) latlongInfo.getBackground(); 
      if (locationMode == 0 || locationMode == 1 || locationMode == 2) { 
       latlongInfo.setText("Please enable high accuracy in your location settings"); 
       drawable.setColor(Color.RED); 
      } else { 
       try { 
        String context = Context.LOCATION_SERVICE; 
        locationManager = (LocationManager) this.getSystemService(context); 
        String provider = LocationManager.GPS_PROVIDER; 
        android.location.Location location = locationManager.getLastKnownLocation(provider); 
        updateWithNewLocation(location); 
        locationManager.requestLocationUpdates(provider, 0, 0, locationListener); 

        param_latitude = df.format(lat).toString(); 
        param_longitude = df.format(lng).toString(); 

        // latlongInfo.setText("Latitude :" + Math.round(lat * 1000000.0)/1000000.0 + " ," + " Longitude :" + Math.round(lng * 1000000.0)/1000000.0); 
        latlongInfo.setText("Latitude : " + param_latitude + " ," + " Longitude : " + param_longitude); 
        latlongInfo.setGravity(Gravity.CENTER); 
        drawable.setColor(Color.GREEN); 
       } catch (SecurityException e) { 
        Log.e("Error", e.toString()); 
       } 
      } 
+0

le principal problème est que vous utilisez 'getLastKnownLocation' pour obtenir l'emplacement mis à jour ... il est très mauvaise idée ... au lieu de cela, vous devez le faire avec' locationListener' ... vous pouvez trouver un exemple de code sur officiall Android site web du guide – Selvin

Répondre

0

Dont utiliser Thread.stop() méthode son deprecated and unsafe

meilleur moyen d'arrêter de fil est de terminer il s `travailler

Créer une variable volatile, quelque chose comme

public volatile boolean threadIsStopped; 

Remplacez votre

while (!isInterrupted()) 

à

while (!threadIsStopped) 

Et puis juste faire vrai

public void onBackPressed() { 
    super.onBackPressed(); 
    threadIsStopped = true; 
    Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class); 
    startActivity(intent); 
    finish(); 
} 

Depuis votre backpress démarre une autre activité et termine actuellement son mieux pour faire une telle chose:

@Override 
protected void onResume() { 
    super.onResume(); 
    threadIsStopped = false; 
    //start thread here 
} 

@Override 
protected void onPause() { 
    super.onResume(); 
    threadIsStopped = true; 
} 

Il y a s no need to stop thread in onBackPressed` du tout.

Notez qu'il ya un retard possible après threadIsStopped est réglé avant fil sera arrêté.

À propos de fil reprenant - dans votre cas, vous venez de créer nouveau thread et le lancer.

Notez également que et onResume seront rappelés si vous modifiez l'orientation de votre périphérique. C'est pourquoi il est fortement recommandé d'utiliser IntentService pour de telles choses.