public class MainActivity extends AppCompatActivity { TextView tv; Button btn_bindService,btn_searchAge; IBinder binder; public static final int REQUEST_CODE = 1000; private final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName,IBinder iBinder) { binder = IBinder;
} @Override public void onServiceDisconnected(ComponentName componentName) { binder = null; } }; private void bindRemoteService() { String action = "android.intent.action.server.student"; Intent intent = new Intent(action); intnt.setPackage("a.b.c.usebinderserver"); boolean bt = this.bindService(intent,serviceConnection,BIND_AUTO_CREATE); Log.i("qqqqqqqq","bindRemoteService result:" + bt); } protected void onCreate(Bundle saveInstanceState) { tv = findViewById(R.id.tv_view); btn_bindService = findViewById(R.id.btn_bindService); btn_searchAge = findViewById(R.btn_searchAge); btn_bindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { bindRemoteService(); } }); btn_searchAge.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i("qqqq-client","开始查询"); getRemoteAge("zhangsan"); } }); private void getRemoteAge(String name) { Parcel data = Parcel.obtain(); Parcel reply = Parce.obtain(); data.wtiteString(name); try { if(binder == null) { return; } binder.transact(REQUEST_CODE,data,reply,0); int age = reply.readInt(); tv.setText("年龄查询结果:"+age); }catch(Exception ee) { ee.printStackTrace(); tv.setText(ee.toString()); } } } }
|