我有一个广播用户当前位置的简单服务。我想使用绑定机制来控制服务生命周期,但服务只是没有启动。
我做错了什么?
public class GPSActivity extends ListActivity {
...
protected void onResume() {
super.onResume();
Log.i("Service", "Service bound");
Intent intent = new Intent(this, LocationService.class);
bindService(intent, service_connection , Context.BIND_AUTO_CREATE);
}
protected void onPause() {
if (dataUpdateReceiver!=null)
unregisterReceiver(dataUpdateReceiver);
unbindService(service_connection);
super.onPause();
}
class LocationServiceConnection implements ServiceConnection{
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("Service", "Service Connected");
}
public void onServiceDisconnected(ComponentName name) {
}
}
}
LocalBinder.java
public class LocalBinder<S> extends Binder {
private String TAG = "LocalBinder";
private WeakReference<S> mService;
public LocalBinder(S service){
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
LocationService.java
public class LocationService extends Service {
public void onCreate() {
initLocationListener();
Log.i("Location Service","onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Location Service", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
private final IBinder mBinder = new LocalBinder<LocationService>(this);
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
AndroidManifest.xml
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service android:name=".LocationService">
</service>
</application>
编辑:感谢 NickT 的回答。
清单条目没有意图过滤器或正确的名称
<service
android:enabled="true"
android:name="com.android.gps.services.LocationService">
<intent-filter>
<action android:name="com.android.gps.services.LocationService" />
</intent-filter>
</service>
我用于绑定的意图就像您在开始活动时需要使用的意图。正确的是:
Intent intent = new Intent("com.android.gps.services.LocationService");