Android Service解綁後再次繫結以及繫結服務出現空指標問題
阿新 • • 發佈:2019-02-02
1——今天在做一個應用的前臺功能的關閉時出現了這麼一個問題,獲取了ibinder例項後,呼叫在Service編寫的方法出現了空指標問題。程式碼如下
private UpdateService.mBinder mBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mBinder = (UpdateService.mBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName componentName) { } }; intent_service_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) {//Switch按鈕 if(b){ Intent intent = new Intent(WeatherAcitivity.this,UpdateService.class); bindService(intent,connection,BIND_AUTO_CREATE); mBinder.stopIntentService(); }else { unbindService(connection); } } });
後來百度了才知道繫結服務是非同步的,所以會出現還沒繫結完服務就開始呼叫方法,當然會報空指標,解決方法是把呼叫方法的程式碼放到onServiceConnected()裡面去,等到繫結結束才開始呼叫服務裡的方法 2——然後又在做前臺服務的重新開啟時遇到了問題,就是呼叫unbind()方法時候,在onServiceDisconnected()沒呼叫裡面的邏輯。不得其解,只能把關閉開啟前臺功能邏輯全部寫在Service的生命週期方法裡去,以下是程式碼
public boolean onUnbind(Intent intent) { Log.d("me", "解綁");//要看到前臺 startForeground(1,notification); return true; } @Override public void onRebind(Intent intent) { //Log.d("me", "重新繫結"); stopForeground(true); super.onRebind(intent); } @Override public IBinder onBind(Intent intent) { //初次繫結 stopForeground(true); return mBinder; }
值得注意的是剛開始,我只重寫了onBind()和unBind()方法,其實如果解綁了一次重新繫結是不會呼叫onBind()方法的,重新繫結會呼叫onRebind()方法,並且前提條件是unBind()方法返回ture。這時候重新繫結onRebind()才會被呼叫,這是要注意的。