2010-12-16 92 views
0

當我的活動開始時,它會創建一個充當服務器的服務。服務器從我的桌面上的python腳本接收原始數據。該服務創建並維護DataManagers,該數據管理器處理來自我的python腳本的所有數據,並在一個哈希映射中鍵入DM的名稱。在任何時候,我需要一個活動來綁定到服務請求從服務和進程的一些數據,當活動暫停,停止或被銷燬時它將解除綁定。Android服務連接?

我相信我的綁定是正確的,但是當我啓動服務時,傳遞的ServiceConnection總是返回null。任何想法是怎麼回事?我的代碼是直接從RemoteService類從Android的 由於被盜 〜Aedon

{代碼編}

結合到PublicService

@Override public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    doBindService(); 
    setContentView(R.layout.homescreen); 
    initView(); 
} 

public void initView() { 
    workbenchs = (Gallery)findViewById(R.id.workbenchs); 
    workbenchs.setMinimumHeight(h/4); 
    workbenchs.setAdapter(new WorkBenchAdapter(this)); 
    workbenchs.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
      Intent it = new Intent(HomeScreen.this, Controller.class); 
      it.putExtra("workbench", arg2); 
      startActivity(it); 
     } 
    }); 
} 

// Gallery Adapter 

public class WorkBenchAdapter extends BaseAdapter { 
    public WorkBenchAdapter(Context c) { } 
    public int getCount() {return mBoundService.getNumBenchs();} 
    public Object getItem(int position) {return position;} 
    public long getItemId(int position) {return position;} 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView i = new ImageView(HomeScreen.this); 
    i.setImageBitmap(mBoundService.getWorkbench(position).toBitmap()); 
     i.setLayoutParams(new Gallery.LayoutParams(w/4, h/4)); 
     return i; 
    } 
} 


// Service Necessities 

public boolean mIsBound = false; 
private PublicService mBoundService; 
private ServiceConnection mConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName className, IBinder service) { 
     mBoundService = ((PublicService.LocalBinder)service).getService(); 
    } 

    public void onServiceDisconnected(ComponentName className) { 
     mBoundService = null; 
    } 
}; 

void doBindService() { 
    Log.d(TAG, "Binding..."); 
    bindService(new Intent(this, PublicService.class), mConnection, Context.BIND_AUTO_CREATE); 
    mIsBound = true; 
    Log.d(TAG, "Bound."); 
} 

void doUnbindService() { 
    if (mIsBound) { 
     Log.d(TAG, "Unbinding..."); 
     unbindService(mConnection); 
     mIsBound = false; 
     Log.d(TAG, "Unbound."); 
    } 
} 

我的問題的主屏幕活動來自於工作臺適配器。當適配器被創建時,它調用get count(它從0開始),但它一直說mBoundService爲空。我已經嘗試在綁定之前啓動服務,並且不會改變任何內容...

+0

服務<application>您可以發佈有關相關內容的代碼? – xandy 2010-12-16 00:33:18

+0

對不起這個爛攤子,該死的東西拒絕阻止我給了它。例如/ ** * /註釋假設爲長行***** – AedonEtLIRA 2010-12-16 16:14:29

+0

要了解如何發佈代碼,請閱讀以下內容:http://stackoverflow.com/editing-help – Cristian 2010-12-16 16:44:34

回答

2

您是否在清單中指定了服務標籤?

在您需要指定這樣的<service android:name="namespace.ServiceName"/>

+0

是的。我認爲發生的事情是,當我在聲明initView()之前很長時間綁定服務時,創建服務並不是在調用initView()時完成的,因此正試圖調用一個空服務。 – AedonEtLIRA 2010-12-16 20:51:02

+0

感謝您的支持。也解決了我的問題。 – CeejeeB 2011-01-23 15:12:32