动态改变UI界面:


Activity:

public class MainActivity extends Activity implements OnClickListener {
    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int val = intent.getIntExtra("name", 0);
            tv.setText(val + "");
        }
    };
    private Button startbtn, stopbtn;
    private TextView tv;
    private Intent i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 动态注册
        registerReceiver(br, new IntentFilter("Action1"));
        startbtn = (Button) findViewById(R.id.start);
        stopbtn = (Button) findViewById(R.id.stop);
        tv = (TextView) findViewById(R.id.tv);
        startbtn.setOnClickListener(this);
        stopbtn.setOnClickListener(this);
        i = new Intent(MainActivity.this, MyService.class);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:
            startService(i);
            break;
        case R.id.stop:
            stopService(i);
            break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(br);// 取消注册
    }
}


Service:

public class MyService extends Service {
    private Timer timer;
    private TimerTask task;
    private int j = 0;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        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();
        task = new TimerTask() {
            @Override
            public void run() {
                j++;
                Intent i = new Intent();
                i.setAction("Action1");
                i.putExtra("name", j);
                sendBroadcast(i);
            }
        };
        timer.schedule(task, 1000, 1000);
    }
    public void stopTimer() {
        timer.cancel();
    }
}


服务一定要记得在配置文件中注册,广播动态注册


运行结果: