Service和Activity交互之广播方式

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

 

二.Broadcast更新Activity中的UI

1.新建一个接口OnUpdateUI,用于回调更新UI

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){
            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);

 

posted @ 2017-04-23 12:01  rorshach  阅读(2952)  评论(0编辑  收藏  举报