Android 程序間通訊
/**
* 客戶端控制介面
*/
public class MainActivity extends Activity {
public static final String TAG = "MainActivity";
// 服務端 AndroidManifest.xml中的intent-filter action宣告的字串
public static final String ACTION = "com.example.playerserver.PlayerService";
private Button playbtn, stopbtn;
private IRemoteService mService;
private boolean isBinded = false;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
isBinded = false;
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IRemoteService.Stub.asInterface(service);
isBinded = true;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doBind();
initViews();
}
private void initViews() {
playbtn = (Button) findViewById(R.id.button1);
stopbtn = (Button) findViewById(R.id.button2);
playbtn.setOnClickListener(clickListener);
stopbtn.setOnClickListener(clickListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onDestroy() {
doUnbind();
super.onDestroy();
}
public void doBind() {
Intent intent = new Intent(ACTION);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
public void doUnbind() {
if (isBinded) {
unbindService(conn);
mService = null;
isBinded = false;
}
}
private OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == playbtn.getId()) {
// play
Log.i(TAG,"play button clicked");
try {
mService.play();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// stop
Log.i(TAG,"stop button clicked");
try {
mService.stop();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
}