<span style="font-size:18px;">package com.gufengxiachen.broadcast; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class LocalService extends Service{ private int progress; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); //得到Activity中传递过来的数据 progress = intent.getIntExtra("progress", 0); //创建一个线程,每隔一秒向Activity发送一个广播,并将progress的新值发送出去 new Thread(){ public void run() { while(progress<100){ progress = progress+1; Intent intent = new Intent(); intent.putExtra("serviceProgress", progress); //设置发送广播的类型,可以随便写一个 intent.setAction("com.gufengxiachen.service"); sendBroadcast(intent); try { sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } }.start(); } } </span>
<span style="font-size:18px;">package com.gufengxiachen.broadcast; 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.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; public class BroadcastReceiverTestActivity extends Activity { private ProgressBar progressBar; private Button button; private int progress = 0; private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); progressBar = (ProgressBar)findViewById(R.id.progressBar); button = (Button)findViewById(R.id.button); progressBar.setMax(100); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //在这里启动服务 Intent intent = new Intent(); intent.putExtra("progress", progress); intent.setClass(BroadcastReceiverTestActivity.this, LocalService.class); startService(intent); } }); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); //注册广播接收器 IntentFilter filter = new IntentFilter(); //设置接收广播的类型,这里要和Service里设置的类型匹配,还可以在AndroidManifest.xml文件中注册 filter.addAction("com.gufengxiachen.service"); this.registerReceiver(myBroadcastReceiver, filter); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); this.unregisterReceiver(myBroadcastReceiver); } //定义一个广播接收器 class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //接收到Service发送的广播信息,得到数据,更新UI progress = intent.getIntExtra("serviceProgress", 0); progressBar.setProgress(progress); } } }</span> http://blog.csdn.net/wustrive_2008/article/details/7188062