代码:
1 /* 2 * 获取当前的位置,并通过短信发送位置到指定号码 3 */ 4 public class LocationService extends Service { 5 6 private LocationManager lm; 7 private MyLocationListener listener; 8 9 @Override 10 public IBinder onBind(Intent intent) { 11 return null; 12 } 13 14 @Override 15 public void onCreate() { 16 super.onCreate(); 17 18 lm = (LocationManager) getSystemService(LOCATION_SERVICE); 19 listener = new MyLocationListener(); 20 Criteria criteria = new Criteria(); 21 criteria.setCostAllowed(true); // 是否允许使用付费 22 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 获取位置的精度 23 String provider = lm.getBestProvider(criteria, true); 24 lm.requestLocationUpdates(provider, 0, 0, listener); 25 } 26 27 class MyLocationListener implements LocationListener { 28 // 位置改变时获取经纬度 29 @Override 30 public void onLocationChanged(Location location) { 31 String j = "jingdu:" + location.getLongitude(); 32 String w = "weidu:" + location.getLatitude(); 33 SharedPreferences mPref = getSharedPreferences("config", 34 MODE_PRIVATE); 35 mPref.edit().putString("location", j + ";" + w).commit(); 36 String savedSafeNumber = mPref.getString("safeNumber", ""); 37 38 double[] locationDouble=LocationUtils.standardToChina(location.getLongitude(), location.getLatitude()); 39 SmsManager.getDefault().sendTextMessage(savedSafeNumber, null, 40 "Phone‘s location:" + locationDouble[0] + ";" + locationDouble[1], null, null); // 把回复的短信内容由中文修改为英文,中文在模拟器上显示为乱码 41 stopSelf(); // 获取到经纬度以后,停止该service 42 } 43 44 // 状态改变时 45 @Override 46 public void onStatusChanged(String provider, int status, Bundle extras) { 47 48 } 49 50 // 提供者可以使用时 51 @Override 52 public void onProviderEnabled(String provider) { 53 54 } 55 56 // 提供者不可以使用时 57 @Override 58 public void onProviderDisabled(String provider) { 59 60 } 61 62 } 63 64 @Override 65 public void onDestroy() { 66 super.onDestroy(); 67 lm.removeUpdates(listener); // 停止所有的定位服务 68 } 69 70 }
时间: 2024-11-10 03:41:54