2013-07-21 56 views
1

我遇到了一個我無法理解的問題。我試圖解決它8天,仍然卡住。我詢問了更多有經驗的開發人員,他們無法回答。所以,請我拼命尋求幫助java android - 簡單綁定服務崩潰

的服務很簡單 - 它有一個方法,但 - 它應該給我的日誌 - getLog()

public class AudioService extends Service{ 

    MyBinder binder = new MyBinder(); 

public void getLog(){Log.d("MyLog","I reached getLog!");} 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return binder; 
    } 
    class MyBinder extends Binder { 
      AudioService getService() { 
       return AudioService.this; 
      } 
      } 
     } 

MainAcivity崩潰,當我試圖達到audioService.getLog( );它不會崩潰,但是,如果我插入行AudioService audioService = new AudioService();但這就是我不想要的 - 我需要設置一個服務來播放音頻,這樣我就可以從一個活動開始播放mp3,並從另一個活動中停止。這裏的MainActivity:

public class MainActivity extends Activity { 
    ServiceConnection sConn; 
    Intent intservice; 
    AudioService audioService ; 

    boolean bound=false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     intservice=new Intent(this,AudioService.class); 
     sConn=new ServiceConnection(){ 

      @Override 
      public void onServiceConnected(ComponentName arg0, IBinder binder) { 
       // TODO Auto-generated method stub 
       audioService = ((AudioService.MyBinder) binder).getService(); 
       bound=true; 
      } 

      @Override 
      public void onServiceDisconnected(ComponentName arg0) { 
       // TODO Auto-generated method stub 
       bound=false; 

      } 

     }; 
      startService(intservice); 

      audioService.getLog(); 

    } 
    @Override 
    protected void onStart() { 
     super.onStart(); 
     bindService(intservice, sConn, Context.BIND_AUTO_CREATE); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (!bound) return; 
     unbindService(sConn); 
     bound = false; 
    } 
} 

的情況下,我在清單亂七八糟的東西,應包括與服務這兒的一部分:

</activity> 
     <service android:enabled="true" android:name="AudioService"></service> 
    </application> 

</manifest> 

我不明白什麼是錯在這裏,所以請給我哪裏做錯了

建議

回答

0

嗯,我發現它是爲什麼。綁定是一個需要時間的過程,現有的每個示例都等待onClick,這意味着Activity在onStart()和onCreate()之間有足夠的時間。在我的情況下,它立即。所以最好的辦法是將public void onServiceConnected(ComponentName arg0,IBinder binder)下的所有Activity都移走。這意味着綁定發生後 - 活動進行得很順利。

希望能對很多人有所幫助)