我认为这会非常简单 - 但这花费的时间比应有的要长。
我只是想将 GPS 坐标发送到 logcat,就是这样。
Intent 很好。每次都会出现“Intent Fired”消息。应用程序只是拒绝去位置更改事件。
如果有人可以看一下并让我知道我的失败之处,我将非常感激。
public class MyReceiver extends IntentService implements LocationListener {
private LocationManager locationManager;
public MyReceiver() {
super("MyReceiver");
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe","Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe","Status");
}
}
谢谢
最佳答案
位置管理器是异步工作的,IntentService
的实现方式是这样的:当 onHandleIntent(Intent Intent)
返回时,服务会自行停止。这意味着它在向您的 onLocationChanged(location location)
方法提供任何位置之前就被销毁了。如果您想使用 IntentService
,则需要在获得您的位置之前阻止 onHandleIntent(Intent Intent)
方法返回,或者使用标准 Service
并在获取 Location
对象时执行 stopSelf
。
public class MyReceiver extends Service implements LocationListener {
private LocationManager locationManager;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_NOT_STICKY;
}
protected void onHandleIntent(Intent intent) {
Log.i("DebugMe", "Intent Fired");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("DebugMe", lat + " " + lon);
locationManager.removeUpdates(this);
// this is where you stop the service
stopSelf();
}
public void onProviderDisabled(String provider) {
Log.d("DebugMe ", "Disabled");
}
public void onProviderEnabled(String provider) {
Log.d("DebugMe", "Enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("DebugMe", "Status");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
请记住,此实现默认情况下不会像 IntentService 那样在单独的线程中运行。
关于java - Android Intent启动时获取GPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789760/