使用Binder.transact()时发生NullPointerException?

时间:2016-03-07 05:27:36

标签: java android

这是我的MainActivty 我放弃了一些粘贴在这里的方法,这使得我的代码缩短为你们

public class MainActivity extends Activity {

private Button btn1,btn2;
private Binder binder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    btn1 = (Button)findViewById(R.id.btn1);
    btn2 = (Button)findViewById(R.id.btn2);
    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, SecondService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);
        }
    });

    btn2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();

            data.writeString("from activity: data");

            try {
                //something wrong here?
                binder.transact(0, data, reply, 0);

                String string = reply.readString();

                System.out.println("actvity   --->"+string);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
ServiceConnection connection = new ServiceConnection() {


    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder binder) {
        // TODO Auto-generated method stub

        MainActivity.this.binder = (Binder)binder;
    }
};

这是我的服务

public class SecondService extends Service{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub

    return  new Mybinder();
}

class Mybinder extends Binder{
    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply,
            int flags) throws RemoteException {
        // TODO Auto-generated method stub

        System.out.println("code---->"+code);

        String string = data.readString();
        System.out.println("s---->"+string);

        reply.writeString("reply from :-->service");
        return super.onTransact(code, data, reply, flags);
    }
}}

下面的Logcat: enter image description here

它表示line55:binder.transact(0,data,reply,0); 有一些问题,但我不知道为什么

任何回答都会欣赏!

1 个答案:

答案 0 :(得分:0)

请在onCreate

中写下此代码
 Intent intent = new Intent();
 intent.setClass(MainActivity.this, SecondService.class);
 bindService(intent, connection, BIND_AUTO_CREATE);