我正试图在Android服务中获取手机的当前GPS位置。 我试着这样做:
Getting Repeated Current Location inside a Service in android?
我的服务如下:
public class MeasurementService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
private Feedback feedback;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
feedback = new Feedback();
if (isNetworkAvailable()) {
new MeasuringTask().execute();
}
return Service.START_NOT_STICKY;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle arg0) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(2000);
...
}
@Override
public void onConnectionSuspended(int arg0) {
}
@Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
private class MeasuringTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
//network access
}
}
每次手机启动时,我都会通过广播接收器启动服务。 当我执行应用程序时,我得到一个java.lang.NoClassDefFoundError:packet.MeasurementService
如果我尝试更改此部分:
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
对此:
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(MeasurmentService.class)
.addOnConnectionFailedListener(MeasurmentService.class)
.addApi(LocationServices.API)
.build();
像其他帖子中推荐的那样,我得到:
GoogleApiClient.Builder类型中的addConnectionCallbacks(GoogleApiClient.ConnectionCallbacks)方法不适用于参数(Class)
想法?非常感谢!
答案 0 :(得分:1)
确保您的服务 LocationListener 来自 com.google.android.gms.location 。
将代码移至onCreate函数。
@Override
public void onCreate() {
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
我在github上有一个示例应用程序,请点击here。
答案 1 :(得分:0)
我终于明白了,这是一个构建错误,我无法解决。
我的解决方案:
我将项目从Eclipse迁移到Android Studio。