Service和Activity交互之广播方式

Posted 罗夏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Service和Activity交互之广播方式相关的知识,希望对你有一定的参考价值。

一.使用场景
如果要通知多个Activity,广播较为适合.但广播较为耗费性能.

 

二.Broadcast更新Activity中的UI

1.新建一个接口OnUpdateUI

public interface OnUpdateUI {
    void updateUI(String i);
}

 

2.BroadcastReceiver代码

public class MyBroadcast extends BroadcastReceiver {

    OnUpdateUI onUpdateUI;
    @Override
    public void onReceive(Context context, Intent intent) {
        String progress = intent.getStringExtra("progress");
        onUpdateUI.updateUI(progress);
    }

    public void SetOnUpdateUI(OnUpdateUI onUpdateUI){
        this.onUpdateUI = onUpdateUI;
    }

}

 

3.Activity中代码:

public class MainActivity extends Activity {

    public static final String FLAG = "UPDATE";
    MyBroadcast myBroadcast;
    TextView tip;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tip = (TextView)findViewById(R.id.tip);

        myBroadcast = new MyBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(FLAG);
        registerReceiver(myBroadcast, intentFilter);

        intent = new Intent(this, MyService.class);
        
    // 更新UI
        myBroadcast.SetOnUpdateUI(new OnUpdateUI() {
            @Override
            public void updateUI(String i) {
                tip.setText(i);
            }
        });
    }

    protected void myClick(View v){
    // 发送广播
        if( v.getId() == R.id.btn ){
            Intent intent = new Intent();
            intent.setAction(FLAG);
            intent.putExtra("progress", System.currentTimeMillis()+"");
            sendBroadcast(intent);
        }

    // 启动服务
        if (v.getId() == R.id.btn2){
            Intent intent = new Intent(this, MyService.class);
            startService(intent);
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(myBroadcast);
        stopService(intent);
        super.onDestroy();
    }
}

三.Service发送广播,广播更新Activity中UI

Service发送广播

Intent it = new Intent();
it.setAction(MainActivity.FLAG);
it.putExtra("progress", i+"");
sendBroadcast(it);

 

以上是关于Service和Activity交互之广播方式的主要内容,如果未能解决你的问题,请参考以下文章

Activity和Service交互之bindService(回调更新UI)

BroadcastReceiver的实例----基于Service的音乐播放器之二

android app中的服务为啥接收不到广播

Android之Service

22 AndroidBroadcast广播机制

安卓,activity上有两个button,想要发送广播给service,怎么区分两个广播