Android 9.0调用高德Service源码

package com.example.mymapapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.model.LatLng;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取gps位置信息的service
 *
 * @author king
 *
 */
@SuppressWarnings("ALL")
public class myService extends Service {
    SensorManager sensormanager;
    private LocationManager locationManager;
    private int i = 0;
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;
    private String notificationId = "serviceid";
    private String notificationName = "servicename";
    NotificationManager notificationManager;
    private LatLng latLng;
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationClientOption mLocationOption = null;
   // private GPSUploadThread myThread;
   List<LatLng> latLngs = new ArrayList<>();
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return new MsgBinder();
    }

    private void showNotification(){
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //创建NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH );
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,getNotification());
    }
    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("title")
                .setContentText("text");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationId);
        }
        Notification notification = builder.build();
        return notification;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate() {
        System.out.println("123");
        super.onCreate();
        showNotification();
        getNotification();

        showNotification();
        getNotification();
//初始化定位

        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景,目前支持三种场景(签到、出行、运动,默认无场景)
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if(null != mLocationClient){
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop,再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(1000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(true);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();

    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。

                    latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                    CoordinateConverter converter = new CoordinateConverter(myService.this);
                    converter.from(CoordinateConverter.CoordType.GPS);
                    converter.coord(latLng);
                    LatLng desLatLng = converter.convert();

                    latLngs.add(desLatLng);
                }else {
                    //定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };


    @SuppressLint("InvalidWakeLockTag")
    @Override
    public void onStart(Intent intent, int startId) {
        System.out.println("456");
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        //创建PowerManager对象
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //保持cpu一直运行,不管屏幕是否黑屏
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning");
        wakeLock.acquire();
    }

    /**
     * 实现一个位置变化的监听器
     */
    private final LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            System.out.println("789");
            // TODO Auto-generated method stub
            try {
                FileOutputStream fos = new FileOutputStream("//storage/emulated/0/Function/Data/"+"aded.err");
                String s = String.valueOf(location.getLongitude())+"##"+ String.valueOf(location.getLatitude());
                latLng = new LatLng(location.getLatitude(),location.getLongitude());
                CoordinateConverter converter = new CoordinateConverter(myService.this);
                converter.from(CoordinateConverter.CoordType.GPS);
                converter.coord(latLng);
                LatLng desLatLng = converter.convert();

                latLngs.add(desLatLng);
                fos.write(s.getBytes());
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            /**
             * 此处实现定位上传功能
             */
        }

        // 当位置信息不可获取时
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            /**
             *
             */
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    };

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        // toggleGPS(false);
        if (locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }
        wakeLock.release();
        super.onDestroy();
    }


    public List<LatLng> getProgress() {
        System.out.println("333333");
        if(latLngs.size()==0)
            return null;
        else return latLngs;
    }

    public class MsgBinder extends Binder {
        /**
         * 获取当前Service的实例
         * @return
         */
        public myService getService(){
            return myService.this;
        }
    }

    public interface OnUpdateUI {
        void updateUI(String i);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值