Android綁定遠程服務

方法: java


服務項目目錄結構:
調用方項目目錄結構:



Iservice.aidl文件 android interface definition language 安卓用於項目間使用同一接口的方式:

package com.pas.payservice;

interface IService
{
 	void callpay();
}



全爲public因此不能夠加修飾符, 調用方須要拷貝此文件及包結構

Service核心: android

public IBinder onBind(Intent arg0)
	{
		Log.i(tag, "遠程支付服務:onBind");
		return new MyBinder();
	}

	private class MyBinder extends IService.Stub
	{

		@Override
		public void callpay()
		{
			pay();
		}
		
	}



 



調用方主AC:注意與調用本地服務的api區別

package com.pas.useage;

import com.pas.payservice.IService;

import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity
{
	private Intent intent;
	private IService binder;
	private MyConn conn;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		intent = new Intent();
		intent.setAction("com.pas.alipay");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void bind(View v)
	{
		conn = new MyConn();
		startService(intent);
		bindService(intent, conn, BIND_AUTO_CREATE);
	}

	private class MyConn implements ServiceConnection
	{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service)
		{
			binder = IService.Stub.asInterface(service);
		}

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

		}

	}

	public void call(View v)
	{
		try
		{
			binder.callpay();
		} catch (RemoteException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	protected void onDestroy()
	{
		try
		{
			if (conn != null)
			{
				unbindService(conn);
			}
		} catch (Exception e)
		{
			// TODO: handle exception
		}
		
		super.onDestroy();
	}
}
相關文章
相關標籤/搜索