有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在我的应用程序中启用网络和gps定位?

我正在尝试获取用户的位置:

//获取GPS状态

isGPSEnabled = locationManage.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            Log.e(MyLogger.TAG, "Non providers are enabled");

我需要用户设置enable network locationturn on GPS

我如何帮助用户完成这些选项

  1. open the device settings page and return to my activity on back press.

  2. change these two device settings from within my application only?

这意味着打开一个确认对话框来启用这两个设置


共 (3) 个答案

  1. # 2 楼答案

    startActivityForResult(新意图(android.provider.Settings.ACTION\u LOCATION\u SOURCE\u Settings),0)

  2. # 3 楼答案

    在4.1之后,在代码中更改这些设置是不可能的(它们可能是打开它的一个变通方法,因为有一个bug see here),但在4.3或4.4上不起作用,或者你需要根手机,你可以做的是向用户显示一个对话框,以转到设置以启用GPS

    public static void LocationAlertDialog(final Context context) {
    
        AlertDialog.Builder d = new AlertDialog.Builder(context);
        d.setTitle("No Providers");
        d.setMessage("Unfortunately, you don't have any providers to get your location, would you like to turn on your GPS?");
    
        d.setNegativeButton(context.getResources().getString(R.string.dialogCancel), new OnClickListener() {
    
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            }
        });
    
        d.setPositiveButton(context.getResources().getString(R.string.dialogAccept), new OnClickListener() {
    
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivityForResult(i, 0);
            }
        });
    
        d.show();
    }
    

    调用中的上一个函数

    if (!isGPSEnabled && !isNetworkEnabled) {
            LocationAlertDialog(this);
            Log.e(MyLogger.TAG, "Non providers are enabled");
    

    然后在onActivityResult中,您可以检查代码0是否已打开GPS