Service服务进程间通讯&Parcelable传递复杂数据

又是固定的模式,熟能生巧

service服务器端

Person.java 实现 Parcelable接口

package com.example.remoteparceservive;

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
	private int age;
	private String name;
	//标配的实现接口
    public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        public Person[] newArray(int size) {
            return new Person[size];
        }
    };
    public Person(){
    	
    }
    private Person(Parcel in){
    	readFromParcel(in);
    }


	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel arg0, int arg1) {//写的顺序必须跟读的顺序一致
		// TODO Auto-generated method stub
		arg0.writeInt(age);
		arg0.writeString(name);

	}
	public void readFromParcel(Parcel in){
		age = in.readInt();
		name = in.readString();
	}
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


对应的Persion.aidl,因为我们定义了Person.java,所以gen目录下不会再生成

package com.example.remoteparceservive;
parcelable Person;


IStockQuoteService.aidl 要使用Person类型,实现传递复杂数据

//in 表示值由客户端设置,out表示值由服务设置,inout表示客户端服务端都设置了该值

package com.example.remoteparceservive;
import com.example.remoteparceservive.Person;
interface IStockQuoteService
{
	String getQuote(in String ticker,in Person requester);
}


实现服务器端StockQuoteService2.java

package com.example.remoteparceservive;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class StockQuoteService2 extends Service {
	private NotificationManager notificationMgr;
	private int mNotificationId;
	//实现 aidl中方法
	public class StockQuoteServiceImpl extends IStockQuoteService.Stub{

		@Override
		public String getQuote(String ticker, Person requester)
				throws RemoteException {
			// TODO Auto-generated method stub
			return requester.getName()+ticker;
		}
		
	}
    @Override
    public void onCreate() {
        super.onCreate();

        notificationMgr =
                (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        displayNotificationMessage("onCreate() called in StockQuoteService2");
    }

    @Override
    public void onDestroy()
    {
        displayNotificationMessage("onDestroy() called in StockQuoteService2");
        // Clear all notifications from this service
        notificationMgr.cancelAll();
        super.onDestroy();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        displayNotificationMessage("onBind() called in StockQuoteService2");
        return new StockQuoteServiceImpl(); //返回AIDL对象
    }

    private void displayNotificationMessage(String message)
    {
        Notification notification = new Notification(R.drawable.ic_launcher, 
message,System.currentTimeMillis());

        PendingIntent contentIntent = 
PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        notification.setLatestEventInfo(this, "StockQuoteService2",message, 
contentIntent);

        notification.flags = Notification.FLAG_NO_CLEAR;

        notificationMgr.notify(mNotificationId, notification);
    }
	

}


最后就是在AndroidManifest.xml中声明服务,注意与本地service声明不同。

        <service android:name="StockQuoteService2">
            <intent-filter >
                <action android:name="com.example.remoteparceservive.IStockQuoteService"/>
            </intent-filter>
        </service>

客户端,从新建个应用

连同包路径拷贝Person.java,Person.aidl,IStockQuoteService.aidl到客户端应用的目录下,以便客户端可以找到调用里面的函数

MainActivity.java

package com.example.remoteparceclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.remoteparceservive.*;

public class MainActivity extends Activity {
	private IStockQuoteService stockService = null;
	
	private Button bindBtn;
	private Button callBtn;
	private Button unbindBtn;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                 bindService(new Intent(IStockQuoteService.class
                         .getName()),
                            serConn, Context.BIND_AUTO_CREATE);
                 bindBtn.setEnabled(false);
                 callBtn.setEnabled(true);
                 unbindBtn.setEnabled(true);
            }});

        callBtn = (Button)findViewById(R.id.callBtn);
        callBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                callService();
            }});
        callBtn.setEnabled(false);
        
        unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View view) {
                unbindService(serConn);
                bindBtn.setEnabled(true);
                callBtn.setEnabled(false);
                unbindBtn.setEnabled(false);
            }});
        unbindBtn.setEnabled(false);
    }

    private void callService() {
        try {
        	Person person = new Person();
        	person.setAge(47);
        	person.setName("Dave");
            String response = stockService.getQuote("SYH", person);
            Toast.makeText(MainActivity.this, "Value from service is "+response, 
Toast.LENGTH_SHORT).show();
        } catch (RemoteException ee) {
        }
    }

    private ServiceConnection serConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            stockService = IStockQuoteService.Stub.asInterface(service);
            callService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        	stockService = null;
        }
    };
}


XML布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  android:id="@+id/bindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Bind"
    />

    <Button android:id="@+id/callBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Call Again"
    />

    <Button android:id="@+id/unbindBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UnBind"
    />
</LinearLayout>




     





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值