0

我有一个使用 GPS 的应用程序,在用户采取行动的活动中,当按下“获取位置”按钮时,它会出现一个警报对话框,用户从那里启用 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();
    }
4

1 回答 1

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();
}

将代码移动到活动将是更好的选择,否则您需要向服务发送一些消息以通知活动有关该操作的信息。

于 2013-05-04T13:16:48.037 回答