繁体   English   中英

android bindService()NullPointerException

[英]android bindService() NullPointerException

以下代码不断抛出空指针异常...

 public class MainActivity extends Activity implements OnClickListener{ Button but; Button but2; LocalBinder binder; @Override protected void 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 = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { Log.d("D1", "connecting"); binder = (LocalBinder) arg1; } @Override public void onServiceDisconnected(ComponentName arg0) { Log.d("D1", "disconnecting"); } }; public static class ServiceTest extends Service{ @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return new LocalBinder(); } public class LocalBinder extends Binder{ public void toast(){ Toast.makeText(getApplicationContext(), "hope this works", Toast.LENGTH_LONG).show(); } } } @Override public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), ServiceTest.LocalBinder.class); bindService(i, connection, Context.BIND_AUTO_CREATE); Toast.makeText(getApplicationContext(), "bind completed", Toast.LENGTH_LONG).show(); } public void binderMethod(View v){ binder.toast(); } } 

我猜这是因为onServiceConnected无法执行,导致绑定程序保持为空。 (but按钮将服务绑定到活动,而but2执行bind.toast();-按下but2时抛出异常)

基本上,问题是:为什么onServiceConnected不执行?

我认为,该意图应该导致服务,而不是服务中的绑定器: Intent i = new Intent(getApplicationContext(), ServiceTest.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM