Android AIDL(介面定義語言)簡單理解和基本使用方法
阿新 • • 發佈:2019-01-01
public class MainActivity extends Activity implements OnClickListener { Button btnBind, btnPlay, btnPause; IMyService mBinder; // 介面的一個引用 boolean mIsBind = false; // 繫結值為true,未綁定製為false; private ServiceConnection mConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { /* * 獲得另一個程序中的Service傳遞過來的IBinder物件-service, * 用IMyService.Stub.asInterface方法轉換該物件,這點與程序內的通訊不同 */ mBinder = IMyService.Stub.asInterface(service); mIsBind = true; Log.i("MainActivity", "onServiceConnected...."); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnBind = (Button) findViewById(R.id.btn_bind); btnPlay = (Button) findViewById(R.id.btn_play); btnPause = (Button) findViewById(R.id.btn_pause); btnBind.setOnClickListener(this); btnPlay.setOnClickListener(this); btnPause.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(); int btn = v.getId(); switch (btn) { case R.id.btn_bind: intent.setAction(Constant.ACTION_AIDL); bindService(intent, mConn, BIND_AUTO_CREATE); //繫結服務 break; case R.id.btn_play: if (mIsBind){ try { mBinder.play(); //呼叫IMyService介面的方法,服務端的邏輯就可以使用 } catch (RemoteException e) { e.printStackTrace(); }//呼叫service中的play() } break; case R.id.btn_pause: if(mIsBind){ try { mBinder.pause(); //呼叫IMyService介面的方法 } catch (Exception e) { e.printStackTrace(); } } break; } } }