如何在Android中的IntentService中获取用户的当前位置?

时间:2013-10-17 12:33:08

标签: android android-service locationmanager

这就是我想要做的。 我有主Activity调用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位置的功能。如何使用服务/意图服务/广播接收器实现这一功能。请帮忙..