这就是我想要做的。我有调用 BroadcastReceiver 名称 SmsAlarmReceiver 的主要活动。
Intent i = new Intent(SmsAlarmReceiver.ALARM_ACTION);
sendBroadcast(i);
现在我的 SmsAlarmReceiver.java 看起来像:
public class SmsAlarmReceiver extends BroadcastReceiver {
LocationManager locationmanager;
public static final String ALARM_ACTION= "com.example.finaltracking.SMS_REC";
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
locationmanager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent smsintent = new Intent(context,SmsService.class);
PendingIntent pendingintent = PendingIntent.getService(context, 0, smsintent, 0);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1*60*1000,10,pendingintent);
}
}
因此,在此接收器中,我请求使用 pendingIntent 进行位置更新以收听位置变化。
我的名为 SmsService.java 的服务如下所示:
public class SmsService extends IntentService {
public SmsService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
Location location = (Location) bundle.get(LocationManager.KEY_LOCATION_CHANGED);
Log.d("msg", "Loc is " + location.getLatitude() +","+ location.getLongitude());
sendMessage("983******","msg is " + location.getLatitude()+"," +location.getLongitude());
}
private void sendMessage(String rec,String msg){
//PendingIntent intent = PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);
SmsManager sms = SmsManager.getDefault();
//Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
ArrayList<String> parts = sms.divideMessage(msg);
sms.sendMultipartTextMessage(rec,null, parts,null, null);
}
}
我的应用程序未强制关闭,但无法将消息发送到指定的接收者。
有没有更好的替代方案。简而言之,一旦用户启用了跟踪功能,我想实现每 5 分钟发送一次用户的 GPS 位置的功能。如何使用服务/意图服务/广播接收器来实现这个功能?请帮助。 .