Service与Activity通信
1、实现步骤:
2、实例:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MyConn mConn;
private MyService.IBinder mBinder;
private Button mButton;
private Button mButton2;
private boolean isBind = false;
private Intent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mIntent = new Intent(this,MyService.class);
mConn = new MyConn();
bindService(mIntent,mConn,BIND_AUTO_CREATE);
isBind = true;
mButton = findViewById(R.id.button);
mButton.setOnClickListener(this);
mButton2 = findViewById(R.id.button2);
mButton2.setOnClickListener(this);
}
@Override
protected void onDestroy() {
if (isBind){
unbindService(mConn);
}
super.onDestroy();
}
@Override
public void onClick(View v) {
int i = v.getId();
switch (i){
case R.id.button:
mBinder.callMyService(2);
break;
case R.id.button2:
if (isBind){
unbindService(mConn);
isBind = false;
}
break;
}
}
public class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinder = (MyService.IBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
MyService.java
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new IBinder();
}
public void testFun(int num){
if (num==1){
Toast.makeText(getApplicationContext(),"this is one!",Toast.LENGTH_SHORT).show();
}
if (num==2){
Toast.makeText(getApplicationContext(),"this is two!",Toast.LENGTH_SHORT).show();
}
}
注意:一定要在清单文件中添加
<service android:name=".MyService"/>