1、EventBus
1)在需要post事件的地方使用如下语句:
EventBus.getDefault().post(new ReadEvent ("hahahaha"));
post 的内容是一个对象,比如
public class ReadEvent {
private String code = "";
public ReadEvent (String code){
this.code = code;
}
public String getCode(){
return this.code;
}
}
2)在需要接受该事件,进行数据处理的类里面需要进行如下操作:
第一、在onResume里面注册EventBus
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
第二、在onPause里面解注册EventBus
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
第三、在该类里面加上onEvent方法,在onEvent里面可以处理从其他类或者线程里面传过来的数据
public void onEvent(ReadEvent event) {
String code = event.getCode();
......
}
2、Handler
例如,更新UI线程里面的进度条,在UI线程里面直接先定义一个Handler对象,覆盖handleMessage方法,在其中更新UI(或者定义一个类继承Handler,然后再初始化里面new一个那个类的对象也行)
Handler updateBarHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
//显示进度条
progress_bar.setProgress(msg.arg1);
//重新把线程加入到队列中
updateBarHandler .post(updateThread);
}
};
在UI线程里面定义一个Runnable 对象,即开启一个子线程,子线程对数据操作,然后通过sendMessage把数据发到Handler消息队列里面,最后接收进行UI更新
Runnable updateThread= new Runnable()
{
int i = 0;
public void run() {
// TODO Auto-generated method stub
i += 10;
//首先获得一个消息结构
Message msg = updateBarHandler .obtainMessage();
//给消息结构的arg1参数赋值
msg.arg1 = i;
//延时1s
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
//把消息发送到消息队列中
updateBarHandler .sendMessage(msg);
if(i == 100)
//把线程从线程队列中移除
updateBarHandler .removeCallbacks(updateThread);
}
};
3、Broadcast
1)、定义一个继承BroadcastReceiver类的广播接收类,实现onReceive方法
public class BroadCastTest1 extends BroadcastReceiver {
public BroadCastTest1() {
}
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("name");
Toast.makeText(context, "广播------:" + name, Toast.LENGTH_SHORT).show();
}
}
2)、注册该广播类
(1)、静态注册即在AndroidManifest.xml里面注册
<receiver
android:name=".BroadCastTest1"
android:enabled="true"
android:exported="true" >
<intent-filter >
<action android:name="bc.test101" />
</intent-filter>
</receiver>
intent-filter 用于过滤intent
(2)、动态注册即在java代码中注册
BroadCastTest1 bCastTest1 = new BroadCastTest1();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("bc.test102");
MainActivity.this.registerReceiver(bCastTest1, intentFilter);
IntentFilter 用于过滤intent
3)、在需要发送广播的地方使用sendBroadcast发送广播
intent.setAction("bc.test101");
intent.putExtra("name", "静态的");
sendBroadcast(intent);
intent.setAction("bc.test102");
intent.putExtra("name", "动态的");
sendBroadcast(intent);
下面附上一段改写的网上代码,通过开启一个Service,在里面使用广播更新UI界面数据的例子
MainActivity的代码如下:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Intent intent = new Intent();
BroadCastTest1 bCastTest1 = new BroadCastTest1();
public static final int CMD_STOP_SERVICE = 0;
TextView tv;//TextView对象应用
DataReceiver dataReceiver;//BroadcastReceiver对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
findViewById(R.id.send).setOnClickListener(this);
findViewById(R.id.static_register).setOnClickListener(this);
findViewById(R.id.action_register).setOnClickListener(this);
findViewById(R.id.stop_register).setOnClickListener(this);
findViewById(R.id.start_service).setOnClickListener(this);
findViewById(R.id.stop_service).setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
dataReceiver = new DataReceiver();
IntentFilter filter = new IntentFilter();//创建IntentFilter对象
filter.addAction("com.roy.MyActivity");
registerReceiver(dataReceiver, filter);//注册Broadcast Receiver
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.static_register:
intent.setAction("bc.test101");
intent.putExtra("name", "静态的");
sendBroadcast(intent);
break;
case R.id.action_register:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("bc.test102");
MainActivity.this.registerReceiver(bCastTest1, intentFilter);
intent.setAction("bc.test102");
intent.putExtra("name", "动态的");
sendBroadcast(intent);
break;
case R.id.stop_register:
unregisterReceiver(bCastTest1);
break;
case R.id.start_service:
Intent myIntent = new Intent(MainActivity.this, MyService.class);
MainActivity.this.startService(myIntent);//发送Intent启动Service
break;
case R.id.stop_service:
Intent myIntent1 = new Intent();//创建Intent对象
myIntent1.setAction("com.roy.MyService");
myIntent1.putExtra("cmd", CMD_STOP_SERVICE);
sendBroadcast(myIntent1);//发送广播
break;
default:
break;
}
}
private class DataReceiver extends BroadcastReceiver {//继承自BroadcastReceiver的子类
@Override
public void onReceive(Context context, Intent intent) {//重写onReceive方法
double data = intent.getDoubleExtra("data", 0);
tv.setText("Service的数据为:"+data);
}
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(dataReceiver);//取消注册Broadcast Receiver
}
}
下面是布局文件代码:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/static_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="静态发送广播" />
<Button
android:id="@+id/action_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="动态发送广播" />
<Button
android:id="@+id/stop_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消注册广播" />
<View
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="2dp"/>
<TextView
android:id="@+id/tv"
android:text="hahah"
android:textSize="24sp"
android:textColor="#000000"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始服务" />
<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止服务" />
</LinearLayout>
下面是Service代码:
public class MyService extends Service {
CommandReceiver cmdReceiver;
boolean flag;
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
flag = true;
cmdReceiver = new CommandReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter();//创建IntentFilter对象
filter.addAction("com.roy.MyService");
registerReceiver(cmdReceiver, filter);//注册Broadcast Receiver
doJob();//调用方法启动线程
return super.onStartCommand(intent, flags, startId);
}
//方法:
public void doJob(){
new Thread(){
public void run(){
while(flag){
try{//睡眠一段时间
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
Intent intent = new Intent();//创建Intent对象
intent.setAction("com.roy.MyActivity");
intent.putExtra("data", Math.random());
sendBroadcast(intent);//发送广播
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private class CommandReceiver extends BroadcastReceiver {//继承自BroadcastReceiver的子类
@Override
public void onReceive(Context context, Intent intent) {//重写onReceive方法
int cmd = intent.getIntExtra("cmd", -1);//获取Extra信息
if(cmd == MainActivity.CMD_STOP_SERVICE){//如果发来的消息是停止服务
flag = false;//停止线程
stopSelf();//停止服务
}
}
}
}