目录
4.2Service通过BroadCast广播与Activity通信
- public class MyService extends Service {
- String msg;
- public MyService() {
- msg = "Msg from Service";
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return new MyBinder();
- }
-
- public class MyBinder extends Binder{
- public String getMsg(){
- return msg;
- }
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log.i("Service","Service start");
- return super.onStartCommand(intent, flags, startId);
- }
- }
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Intent intent = new Intent(this, MyService.class);
- startService(intent);
- bindService(intent, sc, Context.BIND_AUTO_CREATE);
- }
-
- private ServiceConnection sc = new ServiceConnection() {
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- MyService.MyBinder myBinder = (MyService.MyBinder) service;
- Toast.makeText(MainActivity.this,myBinder.getMsg(),Toast.LENGTH_SHORT).show();
- }
-
- @Override
- public void onServiceDisconnected(ComponentName name) {
- // 连接出现了异常断开了,MyService被杀掉了
- Toast.makeText(getApplicationContext(),"Service被解绑",Toast.LENGTH_SHORT).show();
- Log.i("MainActivity","Service被解绑");
- }
- };
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- //退出记得解绑Service
- unbindService(sc);
- }
- }