【发布时间】:2011-04-28 13:27:28
【问题描述】:
到目前为止,在许多文章、教程、文档中,我们调用 startService() 或 bindService() 都会启动服务。我们也可以同时调用两者,但这是一个不同的故事。如果没有 startService(),我将无法绑定服务。
private void bindTunManagerService(int flags) {
TunnelManagerService.setParentActivity(this);
Intent bindIntent = new Intent(this, TunnelManagerService.class);
startService(bindIntent);
tunManagerServiceStarted = bindService(bindIntent, tunConnection, BIND_AUTO_CREATE);
Log.d(TAG, "tunManagerServiceStarted : " + tunManagerServiceStarted + ", ** tunManagerService = " + tunManagerService );
在上面的代码中,如果我注释 startService(),bindService 返回 false 并且 tunManagerService = null,即使 onServiceConnected 也没有启动,我得到“Unable to sart service intent {...} not found”消息。添加startService后,调用service的onCreate、onStart、onServiceConnected,绑定成功。
在实际使用中,是否需要先startServie & 然后才能bindService()。这意味着没有 startSERve,我们无法绑定服务!如果这句话是错误的,为什么我不启动它就无法绑定服务?
有什么想法吗????
添加代码
服务连接:
private ServiceConnection tunConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG,"onServiceConnected" );
tunManagerService = ITunnelManagerService.Stub.asInterface(service);
doConnect();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG,"onServiceDisconnected" );
tunManagerService = null;
}
};
服务:
public class TunnelManagerService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "TunnelManagerService: onCreate");
setCreatedPreference(true);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
setCreatedPreference(false);
hideNotifConnected();
Log.d(TAG, "TunnelManagerService: onDestroy");
}
private final ITunnelManagerService.Stub binder = new ITunnelManagerService.Stub() {
// contains all methods
}
...............
.............
}
清单:
<activity android:name=".StartUltimate" android:label="@string/app_name"
android:launchMode="singleTask" android:windowSoftInputMode="stateHidden|adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="orange.android.vpn.utilities.TunnelManagerService" android:enabled="true"></service>
我使用 2.3.3 SDK 即 API 10。我从中调用的活动位于“orange.android.vpn”中,服务相关文件分别位于“orange.android.vpn.utilities”包中。
【问题讨论】:
-
你使用什么api级别?在 2.1 上,我让这种行为正常工作。
-
请发布您的服务和您的 ServiceConnection 的代码。另外,你看过 logcat 的输出了吗?它是否显示任何错误?如果是这样,也将其发布在这里。
-
@Jake,不,我找不到那个帖子的副本。
-
已添加服务和服务连接代码。在 logcat 中,我只收到“无法启动服务 Intent {..
..} not found ActivityManager 警告。没有其他异常或错误。