onProviderDisabled - 区分提供者

时间:2011-10-20 14:04:49

标签: android

public void getCurrentLocation(){

 final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

     LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
         //
        }

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

        }

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {
            if(provider=="gps"){
            Toast.makeText(getApplicationContext(), "GPS is off", Toast.LENGTH_LONG).show();

            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
            Log.i("lm_disabled",provider);
        }
      };

  locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);
  locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, locationListener);
}

这似乎是一个合法的代码。但是,if表达式永远不会运行。我调试了我的应用程序,提供程序是“gps”,它是字符串类型 - 但if返回false,我猜...

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

您需要在if语句中执行provider.equals("gps")。在java中,您必须使用.equals()方法比较字符串。在java中,==检查两个对象引用是否匹配,而不是字符串是否相同。有关详细信息,请参阅此StackoverFlow post