通过广播实现简单数据交换前后台数据交换BroadcastReceiver

来源:互联网 发布:nginx 与apache哪个好 编辑:程序博客网 时间:2024/06/05 00:49

通过对BroadcastReceiver的继承,实现从前台传递两个数到后台计算完成后传回前台。从前台onCreate方法中传送数据过去,再在onReceive方法接收后台返回的数据并且通过handler传回主线程再显示,实现图为:


前台java代码为:

package com.pangbao.PangIntentService;import java.util.Random;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.os.Handler;import android.os.Message;import android.util.Log;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {Handler handler=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextView tvA=(TextView) findViewById(R.id.tv_a_id);TextView tvB=(TextView) findViewById(R.id.tv_b_id);final TextView tvC=(TextView) findViewById(R.id.tv_sum_id);Random random = new Random();//循环传递100组随机数到后台for (int i = 0; i < 100; i++) {int a=random.nextInt(11);int b=random.nextInt(11);//界面显示数据tvA.setText(a+"");tvB.setText(b+"");//获取意图Intent service = new Intent(this, PIntentService.class);//数据传递,注意键值对要一一对应service.putExtra("KEYINT",new int[] {a ,b });//启动后台服务startService(service);}// for(int i=0;i<100;i++){// int a=random.nextInt(11);// int b=random.nextInt(11);// tvA.setText(a+"");// tvB.setText(b+"");// try {// Thread.sleep(2000);// } catch (InterruptedException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }// }//实例化BroadcastReceiver对象PangBroadcast receiver=new PangBroadcast();//创建广播接收IntentFilter filter=new IntentFilter();//频道接收器filter.addAction("ACTION");//启动接收,开启接收功能registerReceiver(receiver, filter);//消息机制,更新界面,不会阻塞主线程handler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);//过滤if(msg.what==0){int data=(Integer) msg.obj;tvC.setText(data+"");Log.d("前台获得", data+"");Toast.makeText(MainActivity.this, "和为:"+data, Toast.LENGTH_SHORT).show();}}};}//广播机制//重写两个方法onReceive和onDestroypublic class PangBroadcast extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {//获取服务端发送的广播数据int data=intent.getIntExtra("KEYBROAD", -1);//handler消息机制传送数据Message msg=handler.obtainMessage();msg.what=0;msg.obj=data;handler.sendMessage(msg);}}@Overrideprotected void onDestroy() {super.onDestroy();//关闭服务Intent service = new Intent(this, PIntentService.class);stopService(service);}}
后台java代码:
package com.pangbao.PangIntentService;import android.app.IntentService;import android.content.Intent;import android.os.IBinder;import android.util.Log;//该服务自己动实现线程的系列化,不会出现阻塞主线程onHandleIntentpublic class PIntentService extends IntentService {//固定写法,super里面可以随意传字符串public PIntentService() {super("PIntentService");}public int index = 0;//@Override//public void onCreate() {//// TODO Auto-generated method stub//super.onCreate();//}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overrideprotected void onHandleIntent(Intent intent) {//接收前台消息,int data[]=intent.getIntArrayExtra("KEYINT");Log.d("后台服务", data[0]+"+"+data[1]);//匹配广播,Intent intentBroad=new Intent();intentBroad.setAction("ACTION");//发送广播到前台intentBroad.putExtra("KEYBROAD", (data[0]+data[1]));sendBroadcast(intentBroad);try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//final int id = index++;////Log.d("线程启动", id + "");////try {//Thread.sleep(1000);//} catch (InterruptedException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}//Log.d("线程结束", id + "");}}

xml界面代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.pangbao.PangIntentService.MainActivity" >    <TextView        android:id="@+id/tv_a_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"        android:text="@string/hello_world" />    <TextView        android:id="@+id/tv_b_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"        android:text="@string/hello_world" />    <TextView        android:id="@+id/tv_sum_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"        android:text="@string/hello_world" /></LinearLayout>


0 0