定义一个activity,在activity中定义一个内部广播接收器,并且动态注册该广播接收器:
定义一个后台service,该service定时发送广播:
- package com.zzj.ui.serviceUpdateUIDemo;
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.widget.TextView;
- import com.zzj.ui.R;
- public class MainActivity extends Activity {
- private TextView textView;
- public static final String ACTION_UPDATEUI = "action.updateUI";
- UpdateUIBroadcastReceiver broadcastReceiver;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.service_update_ui);
- textView = (TextView) findViewById(R.id.count_txt);
- // 动态注册广播
- IntentFilter filter = new IntentFilter();
- filter.addAction(ACTION_UPDATEUI);
- broadcastReceiver = new UpdateUIBroadcastReceiver();
- registerReceiver(broadcastReceiver, filter);
- // 启动服务
- Intent intent = new Intent(this, ServiceUpdateUI.class);
- startService(intent);
- }
- /**
- * 定义广播接收器(内部类)
- *
- * @author lenovo
- *
- */
- private class UpdateUIBroadcastReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- textView.setText(String.valueOf(intent.getExtras().getInt("count")));
- }
- }
- @Override
- protected void onDestroy() {
- System.out.println("onDestroy");
- super.onDestroy();
- // 注销广播
- unregisterReceiver(broadcastReceiver);
- }
- }
activity布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="当前人数:" />
- <TextView
- android:id="@+id/count_txt"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
- package com.zzj.ui.serviceUpdateUIDemo;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- public class ServiceUpdateUI extends Service {
- private Timer timer;
- private TimerTask task;
- private int count;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- super.onCreate();
- final Intent intent = new Intent();
- intent.setAction(MainActivity.ACTION_UPDATEUI);
- timer = new Timer();
- task = new TimerTask() {
- @Override
- public void run() {
- intent.putExtra("count", ++count);
- sendBroadcast(intent);
- }
- };
- timer.schedule(task, 1000, 1000);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- timer.cancel();
- }
- }
界面效果:
即使Activity退出再启动,仍然能通过广播接收器得到当前人数。