基于百度定位SDK的定位服务的实现(1),python程序设计和算法基础教程

}



@Override

public int onStartCommand(Intent intent, int flags, int startId) {

    LogUtil.e("--------------MobileLocatorService onStartCommand()----------------");



    if (intent != null) {

        startingMode = intent.getIntExtra("startingMode", -1);

        LogUtil.i("startingMode = " + startingMode);

        if (startingMode == Constant.HANDLER_START_SERVICE) {



            LogUtil.e("-------------手动启动---------------");

            

            // 判断服务是否已开启

            boolean isRun = ServiceUtil.isServiceRun(getApplicationContext(), "com.baidu.location.f");

            LogUtil.i("isRun = " + isRun);

            if (isRun == false) {

                LogUtil.e("MobileLocatorService start Location Service");



                // 没启动,开启定位服务

                mLocationClient.start();

            }

        } else {

            // 关闭手机,再次开启手机。这种情况下,startingMode的值获取不到。

            // 关机重启,这种情况下,startingMode的值可以拿到。

            // if (startingMode == Constant.BOOT_START_SERVICE) {



            LogUtil.e("-------------开机自启动---------------");



            checkNetworkNumber++;



            // 第一次,1分钟后检测网络

            mHandler.postDelayed(new Runnable() {



                @Override

                public void run() {



                    LogUtil.e("--------------第一次检测网络---------------");



                    checkNetwork();



                    Message msg = new Message();

                    msg.arg1 = Constant.CHECK_NETWORK_CONNECT_FLAG;

                    mHandler.sendMessage(msg);



                }

            }, CHECK_NETWORK_DELAY_TIME);



        }



    }



    return Service.START_REDELIVER_INTENT;

}



/**

 * 检测网络是否可用

 */

private void checkNetwork() {

    // 如果网络不可用,开启GPS就没有意义

    if (NetWorkUtil.isNetworkAvailable(mContext)) {

        isOpenNetwork = true;



        if (GPSUtil.isOPen(mContext) == false) {

            // 通知用户GPS未开启

            mNotificationUtil.sendGPSNotification();

        }



        LogUtil.i("MobileLocatorService start Location Service");



        // 开启定位服务

        mLocationClient.start();



    } else {

        // 通知用户网络不可用

        mNotificationUtil.sendNetworkNotification();

    }

}



/**

 * 初始化定位服务,配置相应参数

 */

private void initLocationService() {

    mLocationClient = new LocationClient(this.getApplicationContext());

    mLocationListener = new MyLocationListener();

    mLocationClient.registerLocationListener(mLocationListener);



    LocationClientOption locationOption = new LocationClientOption();

    locationOption.setOpenGps(true);

    locationOption.setCoorType("bd09ll");

    locationOption.disableCache(true);

    locationOption.setPriority(LocationClientOption.GpsFirst);

    locationOption.setScanSpan(DELAY_TIME);

    locationOption.setProdName(this.getString(R.string.loaction_prod_name));



    mLocationClient.setLocOption(locationOption);

}



Handler mHandler = new Handler() {



    @Override

    public void handleMessage(Message msg) {

        int result = msg.arg1;



        switch (result) {

        case Constant.CHECK_NETWORK_CONNECT_FLAG:



            // 第一检测网络,直接过了。(已打开)

            boolean isRun = ServiceUtil.isServiceRun(getApplicationContext(), "com.baidu.location.f");

            LogUtil.i("isRun = " + isRun);

            if (isOpenNetwork && isRun) {

                LogUtil.i("--------------第一次检测网络,直接过了。(已打开)----------------");

                return;

            }



            mTimer = new Timer();

            mTimer.schedule(new TimerTask() {



                @Override

                public void run() {

                    checkNetworkNumber++;

                    LogUtil.i("Timer checkNetworkNumber = " + checkNetworkNumber);



                    checkNetwork();



                    boolean isRun = ServiceUtil.isServiceRun(getApplicationContext(), "com.baidu.location.f");

                    if (isOpenNetwork && isRun) {

                        mNotificationUtil.cancelNotification(Constant.NOTIFICATIO_NETWORK_NOT_OPEN);

                        mTimer.cancel();

                        return;

                    } else {

                        if (checkNetworkNumber == 3) {



                            LogUtil.e("--------------第三次检测网络,还未开启,直接退出应用---------");



                            // 检查网络,提醒了用户三次依然未开,退出应用。

                            mNotificationUtil.cancelNotification(Constant.NOTIFICATIO_NETWORK_NOT_OPEN);

                            mNotificationUtil.cancelNotification(Constant.NOTIFICATIO_GPS_NOT_OPEN);

                            mTimer.cancel();



                            // System.gc();

                            System.exit(0);

                        }

                    }

                }

            }, 0, DELAY_TIME);



            break;



        case Constant.UPLOAD_LOACTION_SUCCESS:

            LogUtil.i("您当前的位置上传服务器成功!");

            // Toast.makeText(getApplicationContext(), "您当前的位置上传服务器成功!", Toast.LENGTH_LONG).show();        

            break;



        case Constant.LOCATION_NETWORK_EXCEPTION:

            LogUtil.e("网络异常!请检查您的网络连接。");

            //  网络异常,没有成功向服务器发起请求。

            // Toast.makeText(getApplicationContext(), "网络异常!请检查您的网络连接。", Toast.LENGTH_LONG).show();



            // 通知用户网络不可用

            mNotificationUtil.sendNetworkNotification();

            break;



        case Constant.LOCATION_NETWORK_CONNECT_FAIL:

            LogUtil.e("网络连接失败,请将网络关闭再重新打开试试!");



            // 通知用户网络不可用

            mNotificationUtil.sendNetworkNotification();

            break;



        case Constant.UPLOAD_LOACTION_FAIL:

            // Toast.makeText(getApplicationContext(), "您当前的位置上传服务器失败!请查看下你的网络状态。", Toast.LENGTH_LONG).show();

            LogUtil.e("您当前的位置上传服务器失败!");

            break;



        default:

            break;

        }

    }

};





class MyLocationListener implements BDLocationListener {

    double longitude;



    double latitude;



    @Override

    public void onReceiveLocation(BDLocation location) {

        if (location == null) {

            return;

        }



        LogUtil.i("BDLocationListener onReceiveLocation()");



        /* location.getLocType()的返回值含义:

           61 : GPS定位结果

           62 : 扫描整合定位依据失败。此时定位结果无效。

           63 : 网络异常,没有成功向服务器发起请求。此时定位结果无效。

           65 : 定位缓存的结果。

           66 : 离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果

           67 : 离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果

           68 : 网络连接失败时,查找本地离线定位时对应的返回结果

           161: 表示网络定位结果

           162~167: 服务端定位失败。*/

        int locType = location.getLocType();



        longitude = location.getLongitude();

        latitude = location.getLatitude();



        // TODO 调试使用

        StringBuffer sb = new StringBuffer(256);

        sb.append(" time : ");

        sb.append(location.getTime());

        sb.append("\n error code : ");

        sb.append(locType);

        sb.append("\n latitude : ");

        sb.append(longitude);

        sb.append("\n longitude : ");

        sb.append(latitude);

        LogUtil.i("BDLocationListene " + sb.toString());



        if (locType == Constant.LOCATION_GPS || locType == Constant.LOCATION_NETWORK) {



             //  GPS定位结果、网络定位结果

             mHandler.post(new Runnable() {



                 @Override

                 public void run() {

                     String userId = "bgao";

                     int result = send(userId, longitude, latitude);

                     

                     Message msg = new Message();

                     msg.arg1 = result;

                     mHandler.sendMessage(msg);

                 }

             });



        } else if (locType == Constant.LOCATION_NETWORK_EXCEPTION || locType == Constant.LOCATION_NETWORK_CONNECT_FAIL) {

            //  网络异常,没有成功向服务器发起请求。

            Message msg = new Message();

            msg.arg1 = locType;

            mHandler.sendMessage(msg);

        }

    }



    @Override

    public void onReceivePoi(BDLocation arg0) {



    }

}



/**

 * 向服务器端当前位置的经纬度

 * @param usetId 用户ID

 * @param longitude 经度值

 * @param latitude 纬度值

 */

private int send(String usetId, double longitude, double latitude) {

    StringBuffer params = new StringBuffer();

    params.append("event=save");

    params.append("¤tPointX=");

    params.append(longitude);

    params.append("¤tPointY=");

    params.append(latitude);

    params.append("&userId=");

    params.append(usetId);



    try {

        InputStream inputStream = HttpRequester.post(Constant.UPLOAD_GPS_URL, params);

        if (inputStream != null) {

            String result = new String(FileUtil.read(inputStream));

            String time = (new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(System.currentTimeMillis());

            LogUtil.e("网络请求返回的结果:result = " + result + "\t 时间:" + time);



            if ("Y".equals(result)) {

                return 1;

            } else if ("N".equals(result)) {

                return 0;

            } else {

                LogUtil.e("服务器端返回的值与预先商定的不否! ");

            }

        } else {

            LogUtil.e("网络请求成功,但是返回的数据流为NULL");

        }

    } catch (IOException e) {

        LogUtil.e("IOException 服务器访问失败!");

        e.printStackTrace();

        return 0;

    }



    return 0;

}



@Override

public void onDestroy() {

    LogUtil.e("---------------MobileLocatorService onDestroy()----------------");



    if (mLocationClient != null && mLocationClient.isStarted()) {

        mLocationClient.stop();

        if (mLocationListener != null) {

            mLocationClient.unRegisterLocationListener(mLocationListener);

        }

    }



    SharedPreferences sp = mContext.getSharedPreferences("MobileLocator", Context.MODE_PRIVATE);

    String result = sp.getString("instruct", null);

    LogUtil.i("MobileLocatorService onDestroy() result = " + result);

    if ("exit".equals(result)) {

        sp.edit().putString("instruct", "true").commit();

        LogUtil.e("---------------MobileLocatorService onDestroy()-----------1-----");

        System.exit(0);

        return;

    }



    LogUtil.e("---------------MobileLocatorService onDestroy()---------2-------");



    // 销毁时重新启动Service

    Intent intent = new Intent(ACTION_MOBILE_LOCATOR_SERVICE);

    intent.putExtra("startingMode", startingMode);

    this.startService(intent);

}

}




       B、启动时系统发出的广播的接收器类源码:  



package com.android.mobile.locator;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import com.android.mobile.locator.utils.Constant;

import com.android.mobile.locator.utils.LogUtil;

/**

  • 类名:BootBroadcastReceiver

  • 功能描述:启动时系统发出的广播的接收器

  • #

  • @author android_ls

*/

public class BootBroadcastReceiver extends BroadcastReceiver {

private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";



@Override

public void onReceive(Context context, Intent intent) {

    LogUtil.i("Boot this system , BootBroadcastReceiver onReceive()");

	

	if (intent.getAction().equals(ACTION_BOOT)) {

	    LogUtil.i("BootBroadcastReceiver onReceive(), MobileLocatorService Start");

	    

	    Intent mIntent = new Intent(MobileLocatorService.ACTION_MOBILE_LOCATOR_SERVICE);

	    mIntent.putExtra("startingMode", Constant.BOOT_START_SERVICE);

		context.startService(mIntent);

	}



}

}




      C、关机时系统发出的广播的接收器类源码:



package com.android.mobile.locator;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import com.android.mobile.locator.utils.LogUtil;

/**

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数同学面临毕业设计项目选题时,很多人都会感到无从下手,尤其是对于计算机专业的学生来说,选择一个合适的题目尤为重要。因为毕业设计不仅是我们在大学四年学习的一个总结,更是展示自己能力的重要机会。

因此收集整理了一份《2024年计算机毕业设计项目大全》,初衷也很简单,就是希望能够帮助提高效率,同时减轻大家的负担。
img
img
img

既有Java、Web、PHP、也有C、小程序、Python等项目供你选择,真正体系化!

由于项目比较多,这里只是将部分目录截图出来,每个节点里面都包含素材文档、项目源码、讲解视频

如果你觉得这些内容对你有帮助,可以添加VX:vip1024c (备注项目大全获取)
img

t android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import com.android.mobile.locator.utils.LogUtil;

/**

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数同学面临毕业设计项目选题时,很多人都会感到无从下手,尤其是对于计算机专业的学生来说,选择一个合适的题目尤为重要。因为毕业设计不仅是我们在大学四年学习的一个总结,更是展示自己能力的重要机会。

因此收集整理了一份《2024年计算机毕业设计项目大全》,初衷也很简单,就是希望能够帮助提高效率,同时减轻大家的负担。
[外链图片转存中…(img-INQblUaZ-1712573632518)]
[外链图片转存中…(img-HAXJEw5d-1712573632519)]
[外链图片转存中…(img-BIS6hO5z-1712573632519)]

既有Java、Web、PHP、也有C、小程序、Python等项目供你选择,真正体系化!

由于项目比较多,这里只是将部分目录截图出来,每个节点里面都包含素材文档、项目源码、讲解视频

如果你觉得这些内容对你有帮助,可以添加VX:vip1024c (备注项目大全获取)
[外链图片转存中…(img-VXgVira7-1712573632519)]

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值