【问题标题】:how to get current location of user in IntentService in Android?如何在 Android 的 IntentService 中获取用户的当前位置?
【发布时间】:2013-10-17 12:33:07
【问题描述】:

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

【问题讨论】:

    标签: android android-service locationmanager


    【解决方案1】:

    【讨论】:

    • 我已经完成了它,但是作为 Java/Android 开发的新手,我没有得到在那个 repo 中编写的代码。有没有其他方法可以解决这个问题?>
    • 我知道基础知识,但我要问的是,为什么 requestlocationupdates 在服务中不能像在活动中那样工作..
    • @Droidwala 你能在这里发布代码吗?你是如何实现它的?谢谢x
    • @ndeokar 我几年前实现了这个。所以,我不太记得我当时实现了什么。但我记得我在上面的答案中发布了第一个链接并对其进行了修改根据我的要求.. 与过去几年相比,关于如何获取定期位置发生了很大变化..
    • 第一个链接失效
    猜你喜欢
    • 2017-01-12
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多