Service、BroadcastReceiver、Activity之间的通讯

    Service、BroadcastReceiver、Activity三者之间能够实现相互通讯,这里咱们经过一个例子来看看其中的一种通讯吧。java

   一:功能android

   首先应该知道,在非UI界面上操做UI是会出错的,也就是说在主线程之外的其余线程上操做主线程中的UI是违法的,可是咱们能够作出以下操做,来避免这种状况的发生。编程

   具体功能:在主界面上,启动后台服务Service,后台处理数据,前台经过BroadcastReceiver得到数据并更新UI。ide

   二:具体实现this

   (1)建立继承自Service的类完成相应方法的重写,以及处理数据的操做。spa

public class MyService extends Service {
    private Timer timer;//声明计时器
    private TimerTask task;//声明计时器Task
    private int index = 101;//倒计时起点变量
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startTimer();//启动计时器
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        stopTimer();//中止计时器
        super.onDestroy();
    }
    public void startTimer() {
        timer = new Timer();//实例化Timer对象
        task = new TimerTask() {//实例化TimerTask
            @Override
            public void run() {
                index--;
                Intent i1 = new Intent();// 不能进行页面的跳转,只能实例化成这样
                i1.setAction("action111");// 设置Intent对象的action属性,以便于在主界面作匹配
                i1.putExtra("name", index);// 携带数据
                sendBroadcast(i1);// 发送广播
            }
        };
        timer.schedule(task, 1000, 1000);// 启动计时器
    }
    // 中止计时器
    public void stopTimer() {
        timer.cancel();
    }
}

(2)在Minifest.xml文件中注册Service线程

<service android:name="MyService"></service>

   (3)主界面中完成Service的启动,数据的接受,UI的更新xml

public class MainActivity extends Activity implements OnClickListener {
    private Button startBtn, stopBtn;//声明主界面的按钮
    private Intent intent;//声明Intent对象
    private TextView tv;//声明主界面显示区
    //建立BroadcastReceiver对象,用来接受Service发过来的消息并处理
    private BroadcastReceiver receiver =new BroadcastReceiver() {
                                                                              
        @Override
        public void onReceive(Context context, Intent intent) {
            int num = intent.getIntExtra("name", 0);//得到后台传过来的,键值为name对应的值
            tv.setText(num+"");//更新主界面UI
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    //找到资源
        startBtn = (Button) findViewById(R.id.start);
        stopBtn = (Button) findViewById(R.id.stop);
    //为按钮加载监听
        startBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
    //找到资源
        tv = (TextView) findViewById(R.id.textView1);
        //动态注册BroadcastReceiver对象,并添加要接收数据的action,匹配成功处理数据,不然不处理
        registerReceiver(receiver, new IntentFilter("action111"));
    //实例化Intent对象
        intent = new Intent(MainActivity.this, MyService.class);
                                                                              
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:
            startService(intent);//启动Service
            break;
        case R.id.stop:
            stopService(intent);//中止Service
            break;
        }
    }
                                                                          
    @Override
    protected void onStop() {
        unregisterReceiver(receiver);//取消动态注册
        super.onStop();
    }
}

   (4)结果对象

   (5)结果分析:blog

   这里的程序主要的过程是:在Service中处理数据,而后将数据经过Intent对象,将数据传给前台,在前台经过BroadcastReceiver接收数据并更新UI。从中咱们能够清晰的看到三者之间的联系与联合使用,在从此的编程中,咱们可能还会用到相似的功能,你们要注意咯。

相关文章
相关标签/搜索