2016-03-07 67 views
1

這裏是我的MainActivty 我丟棄一些方法被粘貼在這裏,使我的代碼更短的u人使用Binder.transact()時發生NullPointerException?

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); 有一些問題,但我不知道爲什麼

任何回答欣賞!

+0

請出示您的清單類。 –

+0

如果你點擊按鈕2而沒有點擊按鈕1,你會得到這個錯誤,因爲你沒有初始化你的活頁夾對象。 –

+0

我有申報清單中的服務,我總是點擊按鈕1之前,我點擊第二個按鈕 –

回答

0

請寫代碼onCreate

Intent intent = new Intent(); 
intent.setClass(MainActivity.this, SecondService.class); 
bindService(intent, connection, BIND_AUTO_CREATE); 
+0

我上點擊的方法寫在Button1的這些代碼」,爲什麼沒有工作 –

+0

它不是要去工作,直到你點擊BUTTON1。 :) –

相關問題