方法:
服务项目目录结构: | 调用方项目目录结构: |
![]() | ![]() |
Iservice.aidl文件 android interface definition language 安卓用于项目间使用同一接口的方式:
package com.pas.payservice;
interface IService
{
void callpay();
}
Service核心:
public IBinder onBind(Intent arg0)
{
Log.i(tag, "远程支付服务:onBind");
return new MyBinder();
}
private class MyBinder extends IService.Stub
{
@Override
public void callpay()
{
pay();
}
}
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();
}
}