Android绑定服务后出现空指针异常问题

Intent intent = new Intent(this, MyService.class);
bindService(intent, conn, BIND_AUTO_CREATE);		
mService.callMethod();

这段代码在第三行会出现空指针异常。

private class MyServiceConnection implements ServiceConnection {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("connected");
			mService = (IService) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}
	}

在ServiceConnection实现类中服务绑定成功的回调方法中的打印内容也没有输出。google了一下,原来是“服务的连接是异构的,绑定后直接使用不能保证已经绑定成功,绑定后立即执行会引发空指针异常”。

解决方案:可以在onCreate的方法中完成绑定操作,只要保证不是绑定后立即执行就ok。

你可能感兴趣的:(Android绑定服务后出现空指针异常问题)