Android中Service使用bindService
同个app间调用(只有一次启动该服务)
BinderActicityA
[java]viewplaincopy在CODE上查看代码片派生到我的代码片
publicclassBinderActicityAextendsActivityimplementsView.OnClickListener{
privateButtonbtn1;
privateButtonbtn2;
privateButtonbtn3;
privateButtonbtn4;
privateBindServicebindService=null;
privatebooleanisBound=false;
privateServiceConnectionconn=newServiceConnection(){
@Override
publicvoidonServiceConnected(ComponentNamename,IBinderservice){
isBound=true;
BindService.MyBinderbinder=(BindService.MyBinder)service;
bindService=binder.getService();
intnum=bindService.getRandomNumber();
Log.v("hjz","numA="+num);
}
//client和service连接意外丢失时,会调用该方法
@Override
publicvoidonServiceDisconnected(ComponentNamename){
Log.v("hjz","onServiceDisconnectedA");
}
};
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binder_main);
findLayoutView();
setLister();
initData();
}
privatevoidfindLayoutView(){
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn3=(Button)findViewById(R.id.btn3);
btn4=(Button)findViewById(R.id.btn4);
}
privatevoidsetLister(){
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
}
privatevoidinitData(){
}
@Override
publicvoidonClick(Viewv){
Intentintent=null;
switch(v.getId()){
caseR.id.btn1:
intent=newIntent(BinderActicityA.this,BindService.class);
intent.putExtra("from","ActivityA");
bindService(intent,conn,BIND_AUTO_CREATE);
break;
caseR.id.btn2:
if(isBound){
isBound=false;
Log.v("hjz","ActicityAisunbindService");
unbindService(conn);
}
break;
caseR.id.btn3:
intent=newIntent(this,BinderActivityB.class);
startActivity(intent);
break;
caseR.id.btn4:
this.finish();
break;
}
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
Log.i("hjz","ActivityA->onDestroy");
}
}
xml
[java]viewplaincopy在CODE上查看代码片派生到我的代码片
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.hh.servicedemo.MainActivity">
|
|