首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓bindService() NullPointerException

安卓bindService() NullPointerException
EN

Stack Overflow用户
提问于 2014-10-25 14:42:38
回答 1查看 455关注 0票数 1

下面的代码一直抛出空指针异常..。

代码语言:javascript
复制
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没有执行,这导致绑定器保持为空。(但是按钮在but2执行binder.toast()时将服务绑定到活动;-当按下but2时抛出异常)

最基本的问题是:为什么onServiceConnected不执行?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-25 17:59:01

我认为,这种意图应该导致服务,而不是服务中的粘合剂:Intent i = new Intent(getApplicationContext(), ServiceTest.class);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26563586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档