次のコードは、nullポインタ例外をスローし続けます...
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が実行されないため、バインダーがnullのままになるためだと思います。(butボタンは、but2がbinder.toast();を実行している間、サービスをアクティビティにバインドします。-but2が押されると、例外がスローされます)
基本的に問題は、なぜonServiceConnectedが実行されないのかということです。
私は、その意図は、サービス中のバインダーではなく、サービスにつながるべきだと思います。 Intent i = new Intent(getApplicationContext(), ServiceTest.class);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加