android bindService() NullPointerException,androidbindservice

來源:互聯網
上載者:User

android bindService() NullPointerException,androidbindservice

android app開發中 下面的代碼報錯誤 ,bindService() NullPointerException


 

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 publicclass MainActivity extendsActivity implementsOnClickListener{ Button but; Button but2; LocalBinder binder; @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); but = (Button) findViewById(R.id.button1); but.setOnClickListener(this); but = (Button) findViewById(R.id.button2); }  ServiceConnection connection = newServiceConnection(){   @Override publicvoid onServiceConnected(ComponentName arg0, IBinder arg1) { Log.d("D1","connecting"); binder = (LocalBinder) arg1;  }   @Override publicvoid onServiceDisconnected(ComponentName arg0) { Log.d("D1","disconnecting");  }  };  publicstatic class ServiceTest extendsService{   @Override publicIBinder onBind(Intent arg0) { // TODO Auto-generated method stub returnnew LocalBinder(); }  publicclass LocalBinder extendsBinder{ publicvoid toast(){ Toast.makeText(getApplicationContext(),"hope this works", Toast.LENGTH_LONG).show(); } } }   @Override publicvoid onClick(View arg0) { Intent i = newIntent(getApplicationContext(), ServiceTest.LocalBinder.class); bindService(i, connection, Context.BIND_AUTO_CREATE); Toast.makeText(getApplicationContext(),"bind completed", Toast.LENGTH_LONG).show(); }  publicvoid binderMethod(View v){ binder.toast(); }}}


我自己分析了下感覺是 onServiceConnected 沒有執行,所以才會引起null 指標

在but2執行調用 binder.toast() 的時候 會綁定 service 和 activity
當我點擊btn2的時候才拋出這個異常.

為什麼 onServiceConnected 沒有執行?

處理方法

 intent 在調用service的時候並沒有綁定service

1 Intent i = newIntent(getApplicationContext(), ServiceTest.class);

 


原文地址:http://www.itmmd.com/201411/95.html 
該文章由 萌萌的IT人 整理髮布,轉載須標明出處。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.