Intent,广播Broadcast,和message数据交替

来源:互联网 发布:java web php 编辑:程序博客网 时间:2024/06/05 07:11

通过intent将数据传到后台进行处理,再将处理完的数据通过广播发送,在主UI中接收广播传送的数据,再通过Message数据传递进行更新主UI,实现两个数相加。

效果图


前台代码

package com.pangbao.service;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.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends Activity {Handler handler = null;PangBroadcast receiver = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btn = null;// 界面布局btn = (Button) findViewById(R.id.btn_id);final EditText etA = (EditText) findViewById(R.id.et_a_id);final EditText etB = (EditText) findViewById(R.id.et_b_id);final TextView tv = (TextView) findViewById(R.id.tv_id);btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 连接服务Intent intentService = new Intent(MainActivity.this,PangService.class);// 数据传递intentService.putExtra(PangbaoStaticService.EXTRAKEYSERVICE,new int[] { Integer.parseInt(etA.getText().toString()),Integer.parseInt(etB.getText().toString()) });// 启动服务MainActivity.this.startService(intentService);// 为接收广播做参数准备receiver = new PangBroadcast();IntentFilter filter = new IntentFilter();// 设置对应参数filter.addAction(PangbaoStaticService.ACTION);// 监听广播,等待广播发送送MainActivity.this.registerReceiver(receiver, filter);}});handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if (msg.what == 0) {// message接收数据更新主UIint data = (Integer) msg.obj;tv.setText(String.valueOf(data));Log.d("主线程总和为:", (Integer) msg.obj + "");}}};}@Overrideprotected void onDestroy() {super.onDestroy();// 关闭对应广播Intent intentService = new Intent(this, PangService.class);stopService(intentService);this.unregisterReceiver(receiver);}public class PangBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// 接收广播发送的数据int data = intent.getIntExtra(PangbaoStaticService.EXTRAKEYBROAD,-1);// message传送数据Message msg = handler.obtainMessage();msg.what = 0;msg.obj = data;handler.sendMessage(msg);}}}

后台代码

package com.pangbao.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class PangService extends Service {@Overridepublic void onCreate() {super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 接收前台Intent传送的数据int data[] = intent.getIntArrayExtra(PangbaoStaticService.EXTRAKEYSERVICE);int value = data[0] + data[1];// 创建广播发送对象Intent intentBroadcast = new Intent();// 广播对接参数intentBroadcast.setAction(PangbaoStaticService.ACTION);// 广播发送数据intentBroadcast.putExtra(PangbaoStaticService.EXTRAKEYBROAD, value);// 发送广播getApplicationContext().sendBroadcast(intentBroadcast);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.e("后台", "销毁");}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}

静态常量最好单独定义一个类

package com.pangbao.service;public class PangbaoStaticService {//公用静态参数public static final String ACTION = "action";public static final String EXTRAKEYSERVICE = "SERVICE";public static final String EXTRAKEYBROAD = "BROAD";}

布局代码

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.pangbao.service.MainActivity" >    <EditText        android:id="@+id/et_a_id"        android:layout_width="match_parent"        android:layout_height="wrap_content"         />    <EditText        android:id="@+id/et_b_id"        android:layout_below="@id/et_a_id"        android:layout_width="match_parent"        android:layout_height="wrap_content"         />    <Button        android:id="@+id/btn_id"        android:layout_below="@id/et_b_id"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="执行"         />    <TextView         android:id="@+id/tv_id"        android:layout_below="@id/btn_id"        android:layout_width="match_parent"        android:layout_height="wrap_content"        /></RelativeLayout>

AndroidManifest中注册

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.pangbao.service"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="14" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".PangService"></service>    </application></manifest>


0 0