android 前后台保活 实现定位数据定时上传并展示轨迹 (下)

上一篇地址: https://blog.csdn.net/qq_40803752/article/details/86304508

上2篇写完了,保活。这一篇写进入业务逻辑。

大概5分钟定一次位置,上传到服务器。并且展示。

定位的话,我这里使用的百度定位,说下一我写的时候一个逻辑错误,就是每次只定一次位置,担心百度定位那个持续定位

不能用,后面测试发现没有这个问题。gps定位基本一样的。 也是通过 保活维护着定位监听。下面放代码,

 

//定位 

public class DownloadService extends Service {
    boolean sign=false;
    public Context mContext=this;
    LocationClient mLocationClient;
    public static final int NOTICE_ID = 100;
    private MediaPlayer mMediaPlayer;
    private DownloadBinder mDownloadBinder;
    private Timer mRunTimer;
    private int mTimeSec;
    private int mTimeMin;
    private int mTimeHour;
    private OnTimeChangeListener mOnTimeChangeListener;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext=this;

        mDownloadBinder = new DownloadBinder();
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        //后台播放无声 音乐
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
        mMediaPlayer.setLooping(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 6.0 以上 jobservice
            useJobServiceForKeepAlive();
        }

        // 通知栏
        showNotification();

    }
    /**
     * 使用JobScheduler进行保活
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void useJobServiceForKeepAlive() {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        if (jobScheduler == null) {
            return;
        }
        jobScheduler.cancelAll();
        JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
        //周期设置为了2s
        builder.setPeriodic(1000 * 10);
        builder.setPersisted(true);
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        int schedule = jobScheduler.schedule(builder.build());
        if (schedule <= 0) {

        }

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("TAG","onStartCommand");
        mContext=this;
        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();
        startRunTimer();
        return START_STICKY;
    }
    private void startPlayMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
        }
    }

    private void stopPlayMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return mDownloadBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("TAG","onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (mManager == null) {
            return;
        }
        mManager.cancel(NOTICE_ID);
        stopRunTimer();
        stopPlayMusic();
        // 重启自己

        if (sign){
            Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
            startService(intent);
        }

    }


    private void startRunTimer() {

        if (mLocationClient == null) {
            initLocation(mContext);
        }

    }

    public boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    private void saveLocation(Context mContext,String latitude, String longitude) {
        OffPointBean bean  =new OffPointBean();
        bean.setLatitude(latitude);
        bean.setLongitude(longitude);
        String s="yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String format = simpleDateFormat.format(new Date());
        bean.setTimestamp(format);
        //
        MyUtils.conserveOfflineGPSinfo(mContext, bean);

    }
    private void initLocation(Context mContext) {
        //定位客户端的设置
        mLocationClient = new LocationClient(mContext);
        //   mLocationListener = new MyLocationListener();
        //注册监听
        mLocationClient.registerLocationListener(BDAblistener);
        //配置定位
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("GCJ02");//坐标类型
        option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
        option.setOpenGps(true);//打开Gps
        option.setScanSpan(300000);//0代表只定位1次
        option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }
    private BDAbstractLocationListener BDAblistener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
         
           final String latitude = location.getLatitude() + "";
            final String longitude = location.getLongitude() + "";
            mTimeSec++;
            if (mOnTimeChangeListener != null) {
                mOnTimeChangeListener.showTime(mTimeSec+"");
            }


//因为百度定位,会出现错误定位信息,所以对数据判断下
            if (!String.valueOf(latitude).contains(".") ||String.valueOf(latitude).contains("E")){
                //   infalistener.getOnetimeLocation(null,GPSUtils.GCJ02);
                //再定位一次
              //  LocationInfoSave.initLocation(mContext,infalistener);

              //  mLocationClient.restart();
                int locType = location.getLocType();

                Log.e("TAG",locType+"");


            }   else {

                //这里判断是否有网络

                boolean networkConnected = isNetworkConnected();

                //保存时候  转84
                double lation = location.getLatitude();
                double longitude1 = location.getLongitude();
                if (networkConnected) {
                    DataControl.addPoint(latitude, longitude, new DataResponse() {
                        @Override
                        public void onSucc(Object response) {

                        }

                        @Override
                        public void onFail(String error) {

                            //失败保存在本地服务器
                            saveLocation(mContext,latitude, longitude);
                        }
                    });
                }else {

                    saveLocation(mContext,latitude, longitude);
                }

            }

        }
    };

    private void stopRunTimer() {
        if (mRunTimer != null) {
            mRunTimer.cancel();
            mRunTimer = null;
        }
        mTimeSec = 0;
        mTimeMin = 0;
        mTimeHour = 0;
        Log.e("TAG","时间为:" + mTimeHour + " : " + mTimeMin + " : " + mTimeSec);
    }

    public interface OnTimeChangeListener {
        void showTime(String time);
    }

    public class DownloadBinder extends Binder {
        public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener) {
            mOnTimeChangeListener = onTimeChangeListener;
        }
        public void setStopStatus(boolean status) {
            sign = status;
        }

    }

    /**
     * 启动前台通知
     */
    private void showNotification() {
        String string = mContext.getResources().getString(R.string.app_name_);
        //创建通知详细信息
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.logo)
                .setContentTitle(string)
                .setContentText("系统后台服务");
      //  Intent intent = new Intent(this, MainProgramActivity.class);
        //创建任务栈Builder
        //获取通知服务
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //获取PendingIntent
        Intent mainIntent = new Intent(this, MainProgramActivity.class);
        PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder .setContentIntent(mainPendingIntent);
        
        //构建通知
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        //显示通知
        nm.notify(NOTICE_ID, notification);
        //启动为前台服务
        startForeground(NOTICE_ID, notification);
    }


}

 

 

启动代码就不发了,下面发展示代码。比较简单

xmL:

public class MapActivity extends BaseActivity {

    BaiduMap mBaiduMap;
    @BindView(R.id.bmapView)MapView mMapView;
//    @tv_share

    private boolean isend=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        ButterKnife.bind(this);
        initView();
        super.setTitle("地图");


    }
/*
联网请求 数据
*/
    private void initData() {
        Intent intent = getIntent();
        String time="";
        String userId = MyUtils.getUserId(mContext);
        if (intent!=null){
            time= intent.getStringExtra("time");
        }
        if (TextUtils.isEmpty(time)) {

            String s="yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s);
            time = simpleDateFormat.format(new Date());
            isend=false;
        }

        DataControl.getPoints(userId, time, new DataResponse() {
            @Override
            public void onSucc(Object response) {
                if (response!=null){
                    final GuijiBean data = (GuijiBean) response;
//展示数据
                    setMapDataView(data);

            }

            @Override
            public void onFail(String error) {
                      Tools.toast(mContext,"数据异常: "+error);
            }
        });
    }


    public void changeData(GuijiBean data){

        List points = data.getPoints();
        List reports = data.getReports();
        //setMapDataView(data);

        if (points!=null){
            for (int i=0;i pointslist = data.getPoints();
        List reports = data.getReports();
        if (pointslist==null &&  reports==null){
            Tools.toast(mContext,"当前没有数据!!!");
            return;
        }

        // 构造折线点坐标
        List pointszhe = new ArrayList();
        for (int i=0; i1 &&i==pointslist.size()-1){
                pointszhe.add(lng);
            }
            if (i==0){
                setPositionCenter(lng);
            }
        }
        //构建分段颜色索引数组
        if (pointszhe.size()>1){

            OverlayOptions ooPolyline = new PolylineOptions().width(10)
                    .color(Color.RED).points(pointszhe);
            //添加在地图中
            Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        }

    }
    /**
     * 设置中心点
     */
    public void setPositionCenter(LatLng latLng) {
      //  LatLng mLatLng= new LatLng(latitude,longitude);
        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(latLng);

        mBaiduMap.animateMapStatus(status);//动画的方式到中间
    }

    private void setMarkerOptionsaaa(LatLng ll, int icon) {
        if (ll == null) return;

        //设置为起点
        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(status);//动画的方式到中间
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(icon);
        MarkerOptions ooD = new MarkerOptions().position(ll).icon(bitmap);
        mBaiduMap.addOverlay(ooD);
    }
}

 

 

Gps,实现后面单独写一篇。包括声音地图,高仿户外app。 

 

你可能感兴趣的:(android,进阶)