2014-04-04 33 views
1

有相同標題的許多問題,但他們沒有幫助。所以我問。Android服務:onServiceConnected()永遠不會被調用綁定

我有一項在我的第一項活動中成功啓動的服務。當切換到第二個活動時,我需要bind與服務。但onServiceConnected永遠不會被調用。

(注:我上emulator工作,並用this example實現綁定)

活動:

public class GameActivity extends NativeActivity implements GroupInfoListener 
{ 
    public SimmobBroker broker;// <- this is my service 
    ServiceConnection cnn= new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName name, 
       IBinder service) { 
      Log.i(TAG,"onServiceConnected"); 
      SimmobBrokerBinder binder = (SimmobBrokerBinder) service; 
      broker = binder.getService(); 
      Log.i(TAG,"onServiceConnected...now initializing the activity"); 
      InitializeActivity();   
     } 
     @Override 
     public void onServiceDisconnected(ComponentName name) { 
     } 
    }; 

     @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     Intent intent = new Intent(this, SimmobBroker.class); 
     getApplicationContext().bindService(intent, cnn, getApplicationContext().BIND_AUTO_CREATE); 
//  InitializeActivity(); 
    } 
}; 

服務:

public class SimmobBroker extends Service { 
    @Override 
    public void onCreate() { 
     Log.i(TAG, "SimmobBroker Created"); 
     super.onCreate(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.i(TAG, "SimmobBroker onStartCommand"); 
     myHandler.post(simmobConnect); 
     return START_STICKY; 
    } 

    @SuppressLint("HandlerLeak") 
    public final Handler myHandler = new Handler() {/*...*/} 

    private final IBinder myBinder = new SimmobBrokerBinder(); 

    public class SimmobBrokerBinder extends Binder { 
     public SimmobBroker getService() { 
      return SimmobBroker.this; 
     } 
    } 
    @Override 
    public IBinder onBind(Intent intent) { 
     return myBinder; 
    } 
}; 

謝謝你你的善意幫助。

回答

0

嘗試直接調用bindService,而不是從應用程序上下文中調用。

bindService(intent, cnn, Context.BIND_AUTO_CREATE) 
相關問題