【问题标题】:Android - get country via GPS errorsAndroid - 通过 GPS 错误获取国家/地区
【发布时间】:2012-06-28 12:49:07
【问题描述】:

你好 StackOverflow :)

我在 onStart(); 中创建了一些代码;确保用户启用 GPS 的方法,以便我可以确定他现在在哪个国家/地区。如果 GPS 被禁用,它应该显示一个警告对话框,提示用户在使用应用程序之前启用 GPS。

由于某种原因,整个代码块似乎无法正常工作。我禁用了 GPS,但什么也没有发生,没有对话,也没有类似的东西。为什么会这样?

这是我的代码:

    @Override
protected void onStart() {
    super.onStart();

    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Geocoder code = new Geocoder(TipCalculatorActivity.this);
    try {
        Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        CountryName = adr.getCountryCode();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!gpsEnabled) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("This application requires GPS connectivity to determine your current country, and deliver you accurate tip ratings. Do you wish to turn GPS on?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        TipCalculatorActivity.this.enableLocationSettings();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        TipCalculatorActivity.this.finish();
                        System.exit(1);
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

private void enableLocationSettings() {
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(settingsIntent);
}

非常感谢您的帮助:)

【问题讨论】:

  • 当 gps 禁用时,alert AlertDialog 是否显示?

标签: android gps android-alertdialog android-sensors


【解决方案1】:

位置 loc = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER);

在您的情况下可能返回 null,因为您的手机没有缓存位置。

所以把你的代码改成

if (loc != null) {
    Geocoder code = new Geocoder(AbcActivity.this);
    try {
        Address adr = (Address) code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        // CountryName = adr.getCountryCode();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

如果您需要查询当前位置,那么您需要开启有效的数据连接或 GPS。 关注 Snippet 将对您有所帮助

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class ShowLocationActivity extends Activity implements LocationListener {
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;


/** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            int lat = (int) (location.getLatitude());
            int lng = (int) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
        } else {
            latituteField.setText("Provider not available");
            longitudeField.setText("Provider not available");
        }
    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }
}

最后确保你添加了以下权限。

< uses - permission android: name = "android.permission.ACCESS_FINE_LOCATION" / > 
< uses - permission android: name = "android.permission.ACCESS_COARSE_LOCATION" / >

【讨论】:

  • 如果 loc 为空,我该怎么办?是否有一些代码可以在没有缓存的情况下获取当前位置?
  • 我似乎在 onPause() 和 onResume() 方法上有一个错误,告诉我“this”不适用,它需要一个 locationListener。我还在所有 onLocationChanged、onStatusChanged、onProviderEnabled、onProviderDisabled 方法中遇到了一个错误。它告诉我删除 @override... 这些方法不应该在 Listener 中吗?
猜你喜欢
  • 2013-10-24
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 2012-12-20
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多