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人 整理髮布,轉載須標明出處。