app2调用app1的服务里面的方法
app1:
清单文件
<service android:name="com.ldw.alipay.payService">
<intent-filter >
<action android:name="com.ldw.pay"/>
</intent-filter>
</service>
payService.java
package com.ldw.alipay;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import com.ldw.alipay.publicbusiness.Stub;
public class payService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new zhongjian();
}
class zhongjian extends Stub{
@Override
public void pay() throws RemoteException {
// TODO Auto-generated method stub
//调用服务的pay方法
payService.this.pay();
}
}
public void pay(){
System.out.println("pay支付");
}
}
publicbusiness.aidl
package com.ldw.alipay;
interface publicbusiness {
void pay();
}
app2
activity_main.xml
<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=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="支付"
android:onClick="click"
/>
</RelativeLayout>
MainActivity.java
package com.ldw.usepay;
import android.app.Activity;
import android.content.ComponentName;
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 com.ldw.alipay.publicbusiness;
import com.ldw.alipay.publicbusiness.Stub;
public class MainActivity extends Activity {
publicbusiness pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.ldw.pay");
//这次用匿名的内部类来实现
bindService(intent, new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
pb = Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}, BIND_AUTO_CREATE);
}
//调用远程服务的支付方法
public void click(View v){
try {
pb.pay();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文介绍了一个应用程序(app1)如何通过定义服务并暴露接口,使得另一个应用程序(app2)能够调用该服务中的方法。具体包括app1中服务的定义、接口声明及其实现,以及app2中如何绑定服务并调用其方法。
2453

被折叠的 条评论
为什么被折叠?



