handler.removeCallbacks(runnable) 调用时不停止处理程序

handler.removeCallbacks(runnable) does not stop the handler when call

我想在几秒钟后获取用户的经度和纬度。 runnable 应该重复该方法几秒钟。

问题:当系统获取经纬度并调用removeCallback方法时handler没有停止继续重复代码

这是我到目前为止编写的代码:

public class LocationActivity extends AppCompatActivity {
 LocationManager locationManager;
 LocationListener locationListener;
 ProgressDialog pd;
 ArrayList < String > carModelAL;
 Spinner spinner;
 SharedPreferences sharedPreferences;
 String CAR_MODEL_URL = "http://192.168.0.195:85/tranxavApi/public/api/get-car-model";
 String modelValue;
 Button btn;
 Intent intent;
 TextView detail, selectModel;
 final static Handler handler = null;
 Runnable runnable;

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);

  if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {   
   if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
   }
  }
 }        
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_location);

  final Handler handler = new Handler();   
  detail = (TextView) findViewById(R.id.detail);
  Typeface type = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensedBold.ttf");
  detail.setTypeface(type);

  selectModel = (TextView) findViewById(R.id.selectModel);
  Typeface typeModel = Typeface.createFromAsset(getAssets(), "fonts/RobotoCondensedBold.ttf");
  detail.setTypeface(typeModel);

  carModelAL = new ArrayList < String > ();
  spinner = (Spinner) findViewById(R.id.carModelSP);
  spinner.setAdapter(new ArrayAdapter < String > (LocationActivity.this, android.R.layout.simple_list_item_1, carModelAL));
  getCarModel(CAR_MODEL_URL);

  sharedPreferences = getApplication().getSharedPreferences("myPref", MODE_PRIVATE);
  String likelyProblem = sharedPreferences.getString("likelyProblem", "");
  Log.i("info", likelyProblem);

  btn = (Button) findViewById(R.id.detailBtn);
  btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) { 
    pd = new ProgressDialog(LocationActivity.this);
    pd.setMessage("\tPlease Wait...");
    pd.setCancelable(false);
    pd.show();

    sharedPreferences = getApplication().getSharedPreferences("myPref", MODE_PRIVATE);
    if (sharedPreferences.contains("email") && sharedPreferences.contains("likelyProblem")) {   
     runnable = new Runnable() {
      @Override
      public void run() {
       String modelSelected = spinner.getSelectedItem().toString();
       String email = sharedPreferences.getString("email", "");
       String likelyProblem = sharedPreferences.getString("likelyProblem", "");
       Log.i("info", likelyProblem);
       latAndLong(modelSelected, email, likelyProblem);
       handler.postDelayed(this, 3000);
      }
     };   
     handler.post(runnable);    
    }
   }
  });
 }

 private void latAndLong(final String modelSelected, final String email, final String likelyProblem) {
  ActivityCompat.requestPermissions(LocationActivity.this, new String[] {
   Manifest.permission.ACCESS_FINE_LOCATION
  }, 1);
  GeoLocation geoLocation = new GeoLocation(getApplicationContext());
  Location l = geoLocation.getLocation();

  if (l != null) {   
   handler.removeCallbacks(runnable);
   pd.dismiss();
   double lat = l.getLatitude();
   double lng = l.getLongitude();
   Toast.makeText(getApplicationContext(), "Lat: " + lat + "\n Lon: " + lng, Toast.LENGTH_LONG).show();
   LocationSender locationSender = new LocationSender(lat, lng, email, modelSelected, likelyProblem);
   sendNetworkRequest(locationSender);

   AlertDialog alertDialog = new AlertDialog.Builder(LocationActivity.this).create();
   alertDialog.setTitle("Alert");
   alertDialog.setMessage("Message has been sent to the mechanic he will be there in 5 mins. After he finishes click procced to continue.");
   alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Proceed >>>",
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int which) {
      //                                    dialog.dismiss();
      intent = new Intent(LocationActivity.this, ProblemsActivity.class);
      startActivity(intent);
     }
    });
   alertDialog.show();
  }

  locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  locationListener = new LocationListener() {

   @Override
   public void onLocationChanged(Location location) {

   }

   @Override
   public void onStatusChanged(String provider, int status, Bundle extras) {

   }

   @Override
   public void onProviderEnabled(String provider) {

   }

   @Override
   public void onProviderDisabled(String provider) {

   }
  };
  if (Build.VERSION.SDK_INT < 23) {
   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
  } else {

   if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[] {
     Manifest.permission.ACCESS_FINE_LOCATION
    }, 1);
   } else {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
   }
  }
 }
}

如有任何帮助,我们将不胜感激。提前致谢!

这似乎是预期的行为,因为您从 latAndLong 方法调用 removeCallback,但您在 运行 中再次调用 postDelayed。 Return 来自 latAndLong 方法的布尔值,并决定是否需要在 Run 方法中再次调用 postDelayed