Android - 引导用户打开位置服务

文章目录

准备

开发环境:

Android Studio 4.1.1
Build #AI-201.8743.12.41.6953283, built on November 5, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true, external.system.auto.import.disabled=true

项目

新建项目,选择 Empty Activity,在配置项目时,我选择的 Minimum SDKAPI 16: Android 4.1 (Jelly Bean)

app\build.gradle 文件(这是默认的,我没有修改):

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.gotoenablelocationservice"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

编辑 src\main\res\layout\activity_main.xml 文件,删除原有的 TextView 元素,新增 Button 元素:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Go To Enable Location Service"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

编辑 MainActivity 文件(主要代码是第 51、57 行):

package com.example.gotoenablelocationservice;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    
    

    private static final int REQUEST_CODE_GPS = 1;

    private Button button = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_GPS) {
    
    
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    
    
                Toast.makeText(MainActivity.this, "用户打开定位服务", Toast.LENGTH_LONG).show();
            } else {
    
    
                Toast.makeText(MainActivity.this, "用户关闭定位服务", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void initView() {
    
    
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                // https://developer.android.google.cn/guide/components/intents-filters?hl=zh-cn#ExampleSend
                // https://developer.android.google.cn/reference/android/content/Intent?hl=zh-cn#resolveActivity(android.content.pm.PackageManager)
                // 判断是否有合适的应用能够处理该 Intent,并且可以安全调用 startActivity()。
                if (intent.resolveActivity(getPackageManager()) != null) {
    
    
                    startActivityForResult(intent, REQUEST_CODE_GPS);
                } else {
    
    
                    Toast.makeText(MainActivity.this, "该设备不支持位置服务", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

参考

Android引导用户打开手机位置服务

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/113409799