让应用程序等到位置服务打开后?

时间:2016-12-20 19:52:14

标签: java android multithreading

我的应用程序依赖于启用的位置服务。

因此,当用户启动应用程序时,会出现一个对话框,它会检查是否启用了位置服务。但是,我希望应用程序暂停,直到用户进入设置页面(在对话框中单击“okay”时将其重定向到)并启用位置服务。一旦他这样做,他应该能够返回到MainActivity并且代码应该在他离开的地方继续。

如果我不让应用程序暂停,代码会继续并尝试执行需要启用位置服务的代码,并且应用程序崩溃。

我目前有这个,所以如何修改它以便等待?

if(!location_enabled) {
    // notify user
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setMessage("Location services are currently not " +
            "enabled. You must enable this in order to continue. Would you like to do this now?");

    dialog.setPositiveButton("Take me to location services", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            // WAIT UNTIL LOCATION SERVICES ENABLED
        }
    });

    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            //EXIT APPLICATION

        }
    });
    dialog.show();
}

if(location_enabled) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
        //DO FANCY STUFF WITH LOCATION
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在案例中轻松使用startActivityForResult

当您启动设置以启用您的位置时,您可以像这样开始这样的意图。

// Declare a global variable first
private final int ACTION_LOCATION_SETTING = 100;

// Now change the onClickListener like this
dialog.setPositiveButton("Take me to location services", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
        Intent locationSettingIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(locationSettingIntent, ACTION_LOCATION_SETTING);
    }
});

现在,当您从位置设置返回时,您将在此处收到回叫。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ACTION_LOCATION_SETTING:
            if (resultCode == Activity.RESULT_OK) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
                    //DO FANCY STUFF WITH LOCATION
                }
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}

简单!