Android bindService () NullPointerException, androidbindservice
The following code in android app development reports an error: 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(); }}} |
I analyzed it myself and thought that onServiceConnected was not executed, so it would cause a null pointer.
When but2 calls binder. toast (), it binds the service and activity.
This exception is thrown when I click btn2.
Why is onServiceConnected not executed?
Solution
Intent did not bind a service when calling the service.
| 1 |
Intent i = newIntent(getApplicationContext(), ServiceTest.class); |
Address: http://www.itmmd.com/201411/95.html
This article is organized and published by Meng IT personnel. The reprinted article must indicate the source.