java - android BindService() 空指针异常

标签 java android

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

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没有执行,导致binder保持为null。 (but按钮将服务绑定(bind)到activity,同时but2执行binder.toast();——按下but2时抛出异常)

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

最佳答案

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

关于java - android BindService() 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563586/

相关文章:

java - 并行使用 ArrayList

java - 抽象类以摆脱 Activity 中的冗余代码

java - 如何在 Android/Java 中获取 wunderground API 的 Json 元素

java - 防止 ProgressDialog 被关闭 onClick 事件

java - 检索数据只给我数据库的第一行,我只想将最后一行插入数据库

java - 尝试使用 MIME 发送 "alternative"但它也出现在有能力的邮件客户端中

java - 没有连接数据库?

java - 是否有独立于平台的方式(Java?)来读取音频 CD 的目录?

java - org.openqa.selenium.SessionNotCreatedException

java - 在 OS X 上设置默认 JRE