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
}
}