我有一个使用GPS的应用程序,在用户采取行动的活动中,按下"获取位置"按钮,它出现一个alertdialog,然后用户启用GPS。
但是,当我退出应用程序或退出该活动时,我希望能够禁用该应用程序。
我读到我必须覆盖onPause方法,但是当我按下后退箭头或按下主页按钮时没有任何反应。
GPSTracker gps;
protected LocationManager locationManager;
boolean isGPSEnabled = true;
boolean isNetworkEnabled = true;
@Override
public void onPause() {
super.onPause();
gps = new GPSTracker(MainActivity.this);
try{
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled && isNetworkEnabled) {
gps.showSettingsAlertDisable();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void showSettingsAlertDisable(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("Do you want to disable GPS?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
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() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
答案 0 :(得分:1)
将您的代码添加到onBackPressed()或finish()
@Override
public void finish() {
if(!isCalledFromAlertDialog) {
// Show Alert Dialog - In onClickListener() set variable
// isCalledFromAlertDialog to true and call finish()
// Don't call super.finish();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(YES,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
isCalledFromAlertDialog = true;
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return;
}
super.finish();
}
将代码移动到活动将是更好的选择,否则您需要从服务发送一些消息以通知活动有关该操作。