安卓8.0定位適配

官方安卓8.0改動介紹

developer.android.google.cn/about/versi…android

截取部分圖片

image.png

根據以上圖片介紹,咱們決定用Service顯示一個前臺通知,將獲取的定位信息傳給Activity。

1.services中bind部分git

public class LocalBinder extends Binder {
                public LocationForegroundService getLocationForegroundService() {
                    //Android O上才顯示通知欄
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        showNotify();
                    }
                    return LocationForegroundService.this;
                }
            }
複製代碼
  1. 顯示後臺定位通知欄github

    private void showNotify() {
         if (channel == null) {
             channel = createNotificationChannel();
         }
         NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), getPackageName());
         Intent intent = new Intent(this, MainActivity.class);
         builder.setContentIntent(PendingIntent.getActivity(this, 0, intent, 0))
                 .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
                 .setSmallIcon(R.mipmap.ic_launcher)
                 .setContentTitle("正在後臺定位")
                 .setContentText("定位進行中")
                 .setWhen(System.currentTimeMillis());
         Notification build = builder.build();
         //調用這個方法把服務設置成前臺服務
         startForeground(110, build);
     }
    
     @TargetApi(Build.VERSION_CODES.O)
     private NotificationChannel createNotificationChannel() {
         NotificationChannel notificationChannel = new NotificationChannel(getPackageName(), getPackageName(), NotificationManager.IMPORTANCE_HIGH);
         NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         notificationManager.createNotificationChannel(notificationChannel);
         return notificationChannel;
     }
    複製代碼

3.獲取定位信息網絡

public Location gps() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = null;
        //不加這段話會致使下面爆紅,(這個俗稱版本壓制,哈哈哈哈哈哈)
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//是否支持Network定位
            //獲取最後的network定位信息
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        }
        //網絡獲取定位爲空時,每隔1秒請求一次
        if (location == null) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locationListener);
        }

        return location;
    }
複製代碼

4.定位監聽ide

public interface LocationCallback {
        /**
         * 當前位置
         */
        void onLocation(Location location);
    }

private LocationCallback mLocationCallback;

public void setLocationCallback(LocationCallback mLocationCallback) {
    this.mLocationCallback = mLocationCallback;
}

private class LocationListener implements android.location.LocationListener {
    public LocationListener(String provider) {
        Log.e(TAG, "LocationListener " + provider);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: " + "當前座標:" + location.getLatitude() + " : " + location.getLongitude());
        if (mLocationCallback != null) {
            mLocationCallback.onLocation(location);
        }
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}
複製代碼

5.記得釋放Serviceui

@Override
    public void onDestroy() {
        stopForeground(true);
        stopSelf();
        super.onDestroy();
    }
複製代碼

services準備工做已經完成,記得在AndroidManifest中註冊

1.Activity中記得請求運行時權限,不然沒法獲取定位this

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e(TAG, "--->onServiceConnected");
        LocationForegroundService locationForegroundService = ((LocationForegroundService.LocalBinder) service).getLocationForegroundService();
        Location location = locationForegroundService.gps();
        if (location != null) {
            txt.setText("經度" + location.getLatitude() + "\n緯度:" + location.getLongitude());
        } else {
            txt.setText("沒法獲取地理位置1111");
        }

        locationForegroundService.setLocationCallback(new LocationForegroundService.LocationCallback() {
            @Override
            public void onLocation(Location location) {
                if (location != null) {
                    txt.setText("經度" + location.getLatitude() + "\n緯度:" + location.getLongitude());
                } else {
                    txt.setText("沒法獲取地理位置2222");
                }
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};
複製代碼

2.安卓8.0獲取定位須要打開定位服務,反正沒法獲取定位信息google

private boolean GPSOpen() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 經過GPS衛星定位,定位級別能夠精確到街(經過24顆衛星定位,在室外和空曠的地方定位準確、速度快)
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 經過WLAN或移動網絡(3G/2G)肯定的位置(也稱做AGPS,輔助GPS定位。主要用於在室內或遮蓋物(建築羣或茂密的深林等)密集的地方定位)
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }


public void getLocation(View view) {
    
    if (android.os.Build.VERSION.SDK_INT >= 26) {
        //判判定位服務開啓沒有,沒有跳轉到設置頁面
        if (!GPSOpen()) {
            Intent i = new Intent();
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    }
    //綁定服務
    Intent intent = new Intent(this, LocationForegroundService.class);
    isBound= bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
複製代碼

3.一樣的Activity銷燬後也要解綁Service,爲了不ServiceConnection空指針須要定義一個變量 isBoundspa

@Override
    protected void onDestroy() {
        if (isBound) {
            unbindService(connection)
            isBound = false
        }
        super.onDestroy();
    }
複製代碼

到此適配已經完成了。看不明白的同窗能夠下載demo查看。demo中無 isBound 變量自行按照文章中的方式添加指針

demo地址:github.com/Lans/gpsdem…

相關文章
相關標籤/搜索