尝试在Android中启动服务时出现java错误
我正在尝试编写一个服务,通过Android中的GPs定位来定位用户。我为此而服务。但是当我尝试启动服务时,总是会出现错误
安卓.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
出现。我已经在google上搜索了这个问题,并在我的源代码中添加了以下行:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
但是错误仍然出现。为了使服务启动时没有任何错误,我可以做些什么?这是我的密码: 主要活动。爪哇:
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
//GPs Standort bestimmung starten
Intent intent;
intent = new Intent(this, Gps_Service.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
initButtons();
}
}
“Gps_service.java”:
public class Gps_Service extends Service implements LocationListener{
private double längengrad = 0.0, breitengrad = 0.0;
LocationManager locationManager;
Address adresse;
String straße, Ort, Land;
@Override
public void onCreate(){
super.onCreate();
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10000, 100, this);
}
@Override
public void onDestroy(){
super.onDestroy();
locationManager.removeUpdates(this);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onLocationChanged(Location location) {
längengrad = location.getLongitude();
breitengrad = location.getLatitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
# 1 楼答案
使用谷歌的Fused Location API,而不是通过GPS运行服务来检索用户的位置
提供的链接提供了关于如何实现它的详细指南,并且在接收位置数据时更加可靠和准确
也不要忘记这个渐变依赖: