##建立一個服務類java
package com.tang.alipay; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public class AplipayService extends Service { @Override public IBinder onBind(Intent intent) { System.out.println("alipay:onBind"); return new MyService(); } private class MyService extends IServiceInterface.Stub { public void callAlipayMethod(String name){ alipayMethod(name);//調用內部方法; } } @Override public boolean onUnbind(Intent intent) { System.out.println("alipay:onUnbind"); return super.onUnbind(intent); } @Override public void onCreate() { System.out.println("alipay:onCreate"); super.onCreate(); } @Override public void onDestroy() { System.out.println("alipay:onDestroy"); super.onDestroy(); } public void alipayMethod(String name) { System.out.println("支付寶中服務的方法"); } }
##配置清單文件android
<service android:name=".AplipayService"> <intent-filter > <action android:name="android.service.tang.alipay"/> </intent-filter> </service>
##抽取一個對外接口IServiceInterface寫完後而後重命名成爲.aidl文件app
重命名成.aidl後綴的時候編輯器會在gen目錄下生成相應.java文件編輯器
package com.tang.alipay; interface IServiceInterface { void callAlipayMethod(String name); }
##在其餘項目中調用這個服務方法ide
###把上面的aidl文件複製一份到項目src項目中;注意包名要和上面同樣code
###調用服務接口
public void bindSer(View view) { Intent intent = new Intent(); intent.setAction("android.service.tang.alipay"); bindService(intent, new MyConn(), BIND_AUTO_CREATE); } private class MyConn implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder ibinder) { is = IServiceInterface.Stub.asInterface(ibinder); } @Override public void onServiceDisconnected(ComponentName name) { } } public void callMethod(View view) { try { is.callAlipayMethod("haah"); } catch (RemoteException e) { e.printStackTrace(); } }