方法: java
服務項目目錄結構: |
調用方項目目錄結構: |
|
|
package com.pas.payservice; interface IService { void callpay(); }
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(); } }
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(); } }