這就是我想要做的。 我有主要Activity調用BroadcastReceiver名稱SmsAlarmReceiver。如何在Android的IntentService中獲取用戶的當前位置?
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位置的功能,一旦用戶啓用了跟蹤功能。我可以如何使用服務/意圖服務/廣播接收器來實現此功能。 ?請幫助..
我已經通過它走了,但作爲一個在的Java/Android開發我沒有得到寫在代碼中的新手repo.Is有任何其他的方式,我可以工作了這一點?> – Droidwala
我知道的基本知識,但我要問的是,爲什麼requestlocationupdates不在服務工作,他們在活動的工作方式.. – Droidwala
我終於明白與實施it.Its工作!感謝 – Droidwala