本文介绍: 前言移动GIS开发经常会使用定位功能,很多时候通过代码里的手写定位代码在Activity中就实现了。虽然比较简单,但是也会有一些问题比如定位慢,代码杂乱。一直都知道可以通过Service进行后台定位,也没有实践过,在网上找了一些代码也都比较乱,还有的代码居然是通过service百度SDK进行定位的,这里记录一下博主如何通过Service实现定位的。AndroidManifest.xml这个文件里主要有两处需要注意:添加权限注册Service<?xml version=”1.0

前言

移动GIS开发经常会使用到定位功能,很多时候通过代码里的手写定位代码在Activity中就实现了。虽然比较简单,但是也会有一些问题,比如定位慢,代码杂乱。一直都知道可以通过Service进行后台定位,也没有实践过,在网上找了一些代码也都比较乱,还有的代码居然是通过service百度SDK进行定位的,这里记录一下博主如何通过Service实现定位的。

AndroidManifest.xml

这个文件里主要有两处需要注意:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationservice">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt;
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;
    <uses-permission android:name="android.permission.INTERNET" /&gt;


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.LocationService">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".LocationServer"/>
    </application>

</manifest>

LocationServer

package com.example.locationservice;


import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;


public class LocationServer extends Service {

    private Callback callback;
    //绑定相关接口
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    public class Binder extends android.os.Binder {
        public LocationServer getService() {
            return LocationServer.this;
        }
    }

    @Override
    public void onCreate() {
        Log.e("sss","创建定位服务");
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//			未授权返回
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0.0f, mLocationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0.0f, mLocationListener);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public void setCallback(Callback callback) {
        this.callback = callback;
    }
    //回调
    public static interface Callback {
        void onDataChange(Location location);
    }
    //定位实现
    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            if(callback!=null){
                callback.onDataChange(location);
            }

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
}

MainActivity

这里使用easypermission的库进行了一个权限申请,注意在build.gradle文件中,添加依赖

  implementation 'pub.devrel:easypermissions:3.0.0'
package com.example.locationservice;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    public static final int RESULT_CODE = 1001;

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

        methodRequiresTwoPermission();
    }

    //动态权限框架
    @AfterPermissionGranted(RESULT_CODE)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
//            final Intent intentStart = new Intent(MainActivity.this, LocationServer.class);
//            startService(intentStart);
            Log.e("sss","绑定服务");
            bindService(new Intent(this, LocationServer.class), this, BIND_AUTO_CREATE);
        } else {

            EasyPermissions.requestPermissions(MainActivity.this, "请求获取您的位置信息本地读写权限",
                    RESULT_CODE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Log.e("ss","绑定回调");
        LocationServer.Binder binder = (LocationServer.Binder) iBinder;
        LocationServer myService = binder.getService();
        myService.setCallback(new LocationServer.Callback() {
            @Override
            public void onDataChange(Location location) {
                Message msg = new Message();
                msg.obj = location;
                handler.sendMessage(msg);
                String strcontent=location.getLatitude()+","+location.getLongitude()+","+location.getAccuracy();
                // 每次写入时,都换行
                String strContent = strcontent + "rn";
                Log.e("定位结果",strContent);
                Toast.makeText(MainActivity.this,strContent,Toast.LENGTH_LONG).show();

            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG);
        }
    };
}

运行结果

运行结果

原文地址:https://blog.csdn.net/GISuuser/article/details/124236956

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_29388.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注