Messenger传送数据到后台进行操作

该方法是将前台的数据传到后台,让后台进行处理。

前台代码

package com.pangbao.messenger;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
	ServiceConnection conn = null;
	private Messenger sender = null;
	private int id = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button btn;
		btn = (Button) findViewById(R.id.btn_bind_id);
		btn.setOnClickListener(this);
		btn = (Button) findViewById(R.id.btn_send_id);
		btn.setOnClickListener(this);
	}

	public void bindService() {
		// 指定是要绑定那个后台
		Intent service = new Intent(MainActivity.this, PangService.class);
		conn = new ServiceConnection() {

			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				// 获取后台对象
				sender = new Messenger(service);
			}
		};
		int flags = Service.BIND_AUTO_CREATE;
		// 绑定后台,bindService方法
		bindService(service, conn, flags);
	}

	public void sendService() {
		id++;
		Message msg = new Message();
		msg.obj = "hello,world!" + id;
		try {
			// 用messenger对象传送数据
			sender.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	// 传随机两个数实现后台相加
	public void sendIntService() {
		// 应用message对象添加数据
		Message msg = new Message();
		msg.obj = new int[] { (int) (Math.random() * 11),
				(int) (Math.random() * 11) };

		try {
			// 用messenger对象传送数据
			sender.send(msg);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 点击选择时间
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_bind_id:
			bindService();
			break;
		case R.id.btn_send_id:
			// sendService();
			sendIntService();
			break;
		default:
			break;
		}

	}

}

后台代码

package com.pangbao.messenger;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class PangService extends Service {
	private Messenger messenger = null;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		// 创建handler
		Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// 后台接收前台消息
				int[] data = (int[]) msg.obj;
				Log.d("后台服务收到消息", data[0] + "+" + data[1] + "="
						+ (data[0] + data[1]));
			}
		};
		// 实例化messenger对象
		messenger = new Messenger(handler);

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		// 通过messenger对象返回IBinder对象 对前台onServiceConnected方法连接
		return messenger.getBinder();
	}

}

布局代码

<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.messenger.MainActivity" >

    <Button
        android:id="@+id/btn_bind_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="92dp"
        android:layout_marginTop="30dp"
        android:text="绑定" />

    <Button
        android:id="@+id/btn_send_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_bind_id"
        android:layout_below="@+id/btn_bind_id"
        android:layout_marginTop="55dp"
        android:text="发送" />

</RelativeLayout>

注意,一点要在AndroidManifest.xml中注册

注册为:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pangbao.messenger"
    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" />
    </application>

</manifest>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值