技術回顧:Android 如何在Service獲取最佳座標以及傳送簡訊到指定的手機
1.在功能清單中新增對應的許可權
---簡訊讀寫許可權
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
---獲取位置的許可權
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><!-- 獲取準確GPS座標的許可權 -->
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /><!-- 允許模擬器模擬位置的許可權 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><!-- 獲取粗略座標的位置許可權(網路定位時使用) -->
2.在功能清單中新增Service
<service android:name="com.smartdot.mobilesafe.service.LocationService"/>
3.Java程式碼
package com.smartdot.mobilesafe.service;
import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
/**
* 繼承Service類,實現LocationListener用於獲取座標資訊。
* @author wangguang
*
public class LocationService extends Service implements LocationListener{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
//獲取未知管理物件
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//以最優的方式或的經緯度物件
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);//不要求海拔資訊
criteria.setBearingRequired(false);//不要求方位資訊
criteria.setCostAllowed(true);//是否允許付費
criteria.setPowerRequirement(Criteria.POWER_LOW);//對電量的要求
criteria.setAccuracy(Criteria.ACCURACY_FINE);//指定獲取經緯度的精確度
String bestProvider = locationManager.getBestProvider(criteria, true);
//在一定時間間隔獲取經緯度座標,
locationManager.requestLocationUpdates(bestProvider, 0, 0, this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public void onLocationChanged(Location location) {
SmsManager sms = SmsManager.getDefault();
double longitude = location.getLongitude();//精度
double latitude = location.getLatitude();//緯度
sms.sendTextMessage("5556", null, "longitude=" + longitude + ",latitude=" + longitude, null,null);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}