我已经在我的应用程序中提供了GPS提醒,但是当我启用我的gps并返回到我的mainactivty时,我的gps提醒再次问我,当我按下googlemaps按钮时再次使用agin。它仅在我关闭程序并重新启动应用程序时才有效
这是我的MainActivityClass。
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps = new GPSTracker(MainActivity.this);
}
我的googlemaps按钮。
public void googlemaps(View view) {
if (gps.canGetLocation()) {
Intent intent = new Intent(this, GoogleMaps.class);
startActivity(intent);
} else {
gps.showSettingsAlert();
}
}
这是我的GPS追踪器类
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
public LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
} else {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10, 2000, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location loc) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
答案 0 :(得分:1)
在显示对话框后,如果已启用GPS,则需要重新测试。从它的外观来看,你在创建类时设置canGetLocation
变量一次(通过调用getLocation()
。添加对'getLocation()in
onResume()的调用`解决你的问题。我建议打破逻辑,看看GPS是否已经启用了自己的方法。