关闭

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

123人阅读 评论(0) 收藏 举报

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

前台代码

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10930次
    • 积分:567
    • 等级:
    • 排名:千里之外
    • 原创:47篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类