首页 > 其他分享 >Android实现GPS定位,不用SDK

Android实现GPS定位,不用SDK

时间:2022-10-25 09:49:02浏览次数:107  
标签:android void location import Android GPS public SDK

权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

创建location文件夹,创建GPSLocationListener

import android.location.Location;
import android.os.Bundle;


public interface GPSLocationListener {
    /**
     * 方法描述:位置信息发生改变时被调用
     *
     * @param location 更新位置后的新的Location对象
     */
    void UpdateLocation(Location location);

    /**
     * 方法描述:provider定位源类型变化时被调用
     *
     * @param provider provider的类型
     * @param status   provider状态
     * @param extras   provider的一些设置参数(如高精度、低功耗等)
     */
    void UpdateStatus(String provider, int status, Bundle extras);

    /**
     * 方法描述:GPS状态发生改变时被调用(GPS手动启动、手动关闭、GPS不在服务区、GPS占时不可用、GPS可用)
     *
     * @param gpsStatus 详见{@link GPSProviderStatus}
     */
    void UpdateGPSProviderStatus(int gpsStatus);
}

GPSLocation类

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import android.os.Bundle;

public class GPSLocation implements LocationListener {
    private GPSLocationListener mGpsLocationListener;

    public GPSLocation(GPSLocationListener gpsLocationListener) {
        this.mGpsLocationListener = gpsLocationListener;
    }

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


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        mGpsLocationListener.UpdateStatus(provider, status, extras);
        switch (status) {
            case LocationProvider.AVAILABLE:
                mGpsLocationListener.UpdateGPSProviderStatus(GPSProviderStatus.GPS_AVAILABLE);
                break;
            case LocationProvider.OUT_OF_SERVICE:
                mGpsLocationListener.UpdateGPSProviderStatus(GPSProviderStatus.GPS_OUT_OF_SERVICE);
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                mGpsLocationListener.UpdateGPSProviderStatus(GPSProviderStatus.GPS_TEMPORARILY_UNAVAILABLE);
                break;
        }
    }

    @Override
    public void onProviderEnabled(String provider) {
        mGpsLocationListener.UpdateGPSProviderStatus(GPSProviderStatus.GPS_ENABLED);
    }

    @Override
    public void onProviderDisabled(String provider) {
        mGpsLocationListener.UpdateGPSProviderStatus(GPSProviderStatus.GPS_DISABLED);
    }
}

管理类GPSLocationManager

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.lang.ref.WeakReference;

/**
 * 类描述:GPS定位的管理类
 */
public class GPSLocationManager {
    private static final String GPS_LOCATION_NAME = LocationManager.GPS_PROVIDER;
    private static GPSLocationManager gpsLocationManager;
    private static Object objLock = new Object();
    private boolean isGpsEnabled;
    private static String mLocateType;
    private WeakReference<Activity> mContext;
    private LocationManager locationManager;
    private GPSLocation mGPSLocation;
    private boolean isOPenGps;
    private long mMinTime;
    private float mMinDistance;

    private GPSLocationManager(Activity context) {
        initData(context);
    }

    private void initData(Activity context) {
        this.mContext = new WeakReference<>(context);
        if (mContext.get() != null) {
            locationManager = (LocationManager) (mContext.get().getSystemService(Context.LOCATION_SERVICE));
        }
        //type:internet
        mLocateType = locationManager.NETWORK_PROVIDER;
        isOPenGps = false;
        mMinTime = 1000;
        mMinDistance = 0;
    }

    public static GPSLocationManager getInstances(Activity context) {
        if (gpsLocationManager == null) {
            synchronized (objLock) {
                if (gpsLocationManager == null) {
                    gpsLocationManager = new GPSLocationManager(context);
                }
            }
        }
        return gpsLocationManager;
    }

    /**
     * @param minTime
     */
    public void setScanSpan(long minTime) {
        this.mMinTime = minTime;
    }

    /**
     * @param minDistance
     */
    public void setMinDistance(float minDistance) {
        this.mMinDistance = minDistance;
    }

    /**
     * @param gpsLocationListener
     */
    public void start(GPSLocationListener gpsLocationListener) {
        this.start(gpsLocationListener, isOPenGps);
    }

    /**
     * @param gpsLocationListener
     * @param isOpenGps
     */
    public void start(GPSLocationListener gpsLocationListener, boolean isOpenGps) {
        this.isOPenGps = isOpenGps;
        if (mContext.get() == null) {
            return;
        }
        mGPSLocation = new GPSLocation(gpsLocationListener);
        isGpsEnabled = locationManager.isProviderEnabled(GPS_LOCATION_NAME);
        if (!isGpsEnabled && isOPenGps) {
            openGPS();
            return;
        }

        if (ActivityCompat.checkSelfPermission(mContext.get(),Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (mContext.get(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        Location lastKnownLocation = locationManager.getLastKnownLocation(mLocateType);
        mGPSLocation.onLocationChanged(lastKnownLocation);

        locationManager.requestLocationUpdates(mLocateType, mMinTime, mMinDistance, mGPSLocation);
    }

    public void openGPS() {
        Toast.makeText(mContext.get(), "please open gps", Toast.LENGTH_SHORT).show();
        if (Build.VERSION.SDK_INT > 15) {
            Intent intent = new Intent(
                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.get().startActivityForResult(intent, 0);
        }
    }


    public void stop() {
        if (mContext.get() != null) {
            if (ActivityCompat.checkSelfPermission(mContext.get(), Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext.get(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            locationManager.removeUpdates(mGPSLocation);
        }
    }
}

GPSProviderStatus类

public class GPSProviderStatus {
    //用户手动开启GPS
    public static final int GPS_ENABLED = 0;
    //用户手动关闭GPS
    public static final int GPS_DISABLED = 1;
    //服务已停止,并且在短时间内不会改变
    public static final int GPS_OUT_OF_SERVICE = 2;
    //服务暂时停止,并且在短时间内会恢复
    public static final int GPS_TEMPORARILY_UNAVAILABLE = 3;
    //服务正常有效
    public static final int GPS_AVAILABLE = 4;
}

然后就可以在Main里直接用了只要implements

public class MainActivity extends AppCompatActivity implements GPSLocationListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GPSLocationManager gpsLocationManager = GPSLocationManager.getInstances(MainActivity.this);
        gpsLocationManager.start(MainActivity.this);    
    }

    @Override
    public void UpdateLocation(Location location) {
        if (location != null) {
            Toast.makeText(MainActivity.this, location.getLongitude() +","+location.getLatitude(), Toast.LENGTH_SHORT).show();
        }

    }
    @Override
    public void UpdateStatus(String provider, int status, Bundle extras) {
        Toast.makeText(MainActivity.this, "定位类型:" + provider, Toast.LENGTH_SHORT).show();
    }
    @Override
    public void UpdateGPSProviderStatus(int gpsStatus) {
    }
}

GitHub地址 下载前给star

标签:android,void,location,import,Android,GPS,public,SDK
From: https://www.cnblogs.com/Frank-dev-blog/p/16823823.html

相关文章

  • Android编译报错:Cannot resolve external dependency com.android.tools.build:gradle
    修改根目录的build.gradle增加 repositories配置,然后再File>SyncProjectwithGradleFiles,再执行Build>RebuildProjectbuildscript{ext{agp_versi......
  • Android APK 文件结构
    序言APK(全称:Androidapplicationpackage,Android应用程序包)是Android操作系统使用的一种应用程序包文件格式,用于分发和安装移动应用及中间件。APK文件基于ZIP文件格式......
  • 在WSL2中 安装 .NET Core SDK 进行Linux 开发工作
    安装WSL1、打开WINDOWS功能,勾选子系统选项​​​​2、打开商店搜索WSL,安装ubuntu我这里的系统版本是:18.04如何查看ubuntu系统版本sudolsb_release-a​​​​3、打开ubuntu......
  • 不依赖SDK的获取OAID -- OAIDHelper
    OAIDHelperOAID作为广告标识符,在OAID_SDK_1.0.25版本及以前支持直接使用,但1.0.25版本支持的设备覆盖不够全面,1.0.26版本及以后需要根据应用包名申请证书文件,且需要企业认......
  • android系统上编写、运行C#代码
    最近找到个好玩的APP,C#Shell(CompilerREPL),可以在安卓系统上编写和运行C#代码,配合sqlite数据库,写了个小爬虫,运行还不错;运行一些小爬虫或者定时任务可以用这个,毕竟手机比......
  • Android 系统调用拦截hook
    本文ASOP源码版本8.1,下面是相关改动文件Changesnotstagedforcommit:(use"gitadd/rm<file>..."toupdatewhatwillbecommitted)(use"gitcheckout--<......
  • 打开Android Studio时提示:adb.exe使用的5037端口被占用了
    打开AndroidStudio时报如下错误提示:方法一1、根据提示查看adb的端口号5037被谁占用cmd打开命令窗口,运行netstat-aon|findstr“5037”找出相应的pid号;2、然后在......
  • android实现网格布局
    效果图  添加依赖implementation'com.github.mtjsoft:GridPager:v3.7.0'layout文件<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="h......
  • Android 获取应用使用情况
    效果图   先建个Unit文件夹,把下面的文件都放进去创建文件DateTransUtilspackagecn.xrick.applicationusetime.Unit;importandroid.util.Log;importjava......
  • android实现pdf阅读器
    添加依赖implementation'com.github.barteksc:android-pdf-viewer:3.1.0-beta.1'MainActivity文件importandroidx.appcompat.app.AppCompatActivity;importan......