2012-07-07 66 views
1

我无法使onServiceConnected()方法运行,这意味着它不会将我的活动绑定到服务。无法将活动绑定到服务

这可能很简单,我错过了 - 但我已经尝试了很多次 - 从头开始​​。

在这里,我们去...

我的服务类

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 

public class QuickService extends Service { 

private final IBinder mBinder = new QuickBinder(this); 

@Override 
public IBinder onBind(Intent intent) { 
    return mBinder; 
} 

} 

我的文件夹类

import android.os.Binder; 

public class QuickBinder extends Binder { 

private final QuickService service; 

public QuickBinder(QuickService service){ 
    this.service = service; 
} 

public QuickService getService(){ 
    return service; 
} 

} 

和...试图绑定到的活动服务。

import android.app.Activity; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.os.Bundle; 
import android.os.IBinder; 

public class QuickActivity extends Activity { 

QuickService mService; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_connecting); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    Intent intent = new Intent(this, QuickService.class); 
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    // Unbind from the service 
     unbindService(mConnection); 
    } 

/** Defines callbacks for service binding, passed to bindService() */ 
private ServiceConnection mConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName className, 
      IBinder service) { 
     Logger.d("Connected!!! :D"); 
     // We've bound to LocalService, cast the IBinder and get LocalService instance 
     QuickBinder binder = (QuickBinder) service; 
     mService = binder.getService(); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 
    } 
}; 
} 

而且,在清单文件中定义的服务 - 如果你认为这是问题。

<service android:name=".QuickService"></service> 

那么,我在这里做错了什么?为什么不调用onServiceConnected()方法?

回答

1

与以下

<service android:name=".QuickService"> 
      <intent-filter> 
       <action android:name=".QuickService .BIND" /> 
       <category android:name="android.intent.category.DEFAULT"/> 
      </intent-filter> 
     </service> 
+0

谢谢,它现在都在工作。我必须去看看为什么你现在需要添加。 – shadrx 2012-07-07 05:29:21

+1

你能解释为什么我需要补充吗? – shadrx 2012-07-07 05:31:16

-1

而是写作的更新:

Intent intent = new Intent(this, QuickService.class); 
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 

你可以写:要启动服务

startService(new Intent(QuickActivity.this, QuickService.class)); 

希望这会帮助你。

+0

是的,但是如果我想要一个可以绑定的服务,那么我认为这并不是真的有帮助。 – shadrx 2012-07-07 05:38:38