29GPS代码的移植

来源:互联网 发布:帝国cms批量删除文章 编辑:程序博客网 时间:2024/06/05 05:19

创建一个GPSService继承Service类,在后台不断监听位置的变化。

package com.ustc.mobilemanager.service;import android.app.Service;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.location.Criteria;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.os.IBinder;public class GPSService extends Service {// 得到位置服务private LocationManager lm;private MyLocationListener listener;@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();// 实例化lm = (LocationManager) getSystemService(LOCATION_SERVICE);// List<String> providers = lm.getAllProviders();// for (String l : providers) {// System.out.println(l);// }listener = new MyLocationListener();// 注册监听位置服务// 给内容提供者设置条件Criteria criteria = new Criteria();criteria.setAccuracy(Criteria.ACCURACY_FINE);String provider = lm.getBestProvider(criteria, true);lm.requestLocationUpdates(provider, 0, 0, listener);}class MyLocationListener implements LocationListener {/** * 当位置改变的时候回调这个方法 *  */@Overridepublic void onLocationChanged(Location location) {// 经度String longitude = "jingdu:" + location.getLongitude() + "\n";// 纬度String latitude = "weidu:" + location.getLatitude()+ "\n";// 精度String accuracy = "accuracy:" + location.getAccuracy()+ "\n";//发短信给安全号码SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);Editor editor = sp.edit();editor.putString("lastlocation", longitude +latitude + accuracy);editor.commit();// TextView textView = new TextView(MainActivity.this);// textView.setText(longitude + "\n" + latitude + "\n" + accuracy);// setContentView(textView);}/** *  * 当状态发生改变的时候 *  */@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {}/** *  *  * 某一个位置提供者可以使用了回调 */@Overridepublic void onProviderEnabled(String provider) {}/** *  *  * 某一个位置提供者不可以使用了回调 */@Overridepublic void onProviderDisabled(String provider) {}}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();// 取消监听位置服务lm.removeUpdates(listener);listener = null;}}

使用SharedPreferences保存最后一次的位置,在SMSReceiver中获取位置,然后作比较。


if ("#*location*#".equals(body)) {// 得到手机的GPSLog.i(TAG, "得到手机的GPS");//启动服务Intent i = new Intent(context,GPSService.class);context.startService(i);SharedPreferences sp = context.getSharedPreferences("config", context.MODE_PRIVATE);String lastlocation = sp.getString("lastlocation", null);if (TextUtils.isEmpty(lastlocation)) {//位置没有得到SmsManager.getDefault().sendTextMessage(sender, null, "正在获取位置中...", null, null);}else {//得到位置了SmsManager.getDefault().sendTextMessage(sender, null, lastlocation, null, null);}// 把这个广播终止掉abortBroadcast();} 




0 0