1 <service
2 android:name=".MyService"
3 android:enabled="true"
4 android:exported="true"></service>
1 public class MyService extends Service {
2 public MyService() {
3 }
4
5 @Override
6 IBinder onBind(Intent intent) {
7 return new MyBinder();//return MyBinder通过ServiceConnection在activity中拿到MyBinder
8 9
10 11 int onStartCommand(Intent intent,int flags,1)">int startId) {
12
13 super.onStartCommand(intent,flags,startId);
14 15
16 public void payService(){
17 Log.i("MyService","payService: --------");
18 19
20 class MyBinder Binder{
21
22 pay(){
23 payService();
24 }通过Binder实例将service中的方法暴露出去
25 26 }
1 Button
2 android:id="@+id/btn_paly"
android:text="Pay"
android:layout_width="wrap_content"
5 android:layout_height="wrap_content" />
class MainActivity AppCompatActivity {
2
3 MyService.MyBinder binder = null;
4 ServiceConnection conn;
5
6 7 protected onCreate(Bundle savedInstanceState) {
8 .onCreate(savedInstanceState);
9 setContentView(R.layout.activity_main);
10
11 Button btnPlay = (Button) findViewById(R.id.btn_paly);
12 conn = new ServiceConnection() {
13 @Override
14 onServiceConnected(ComponentName componentName,IBinder iBinder) {
15 binder = (MyService.MyBinder) iBinder;
16 }
17
19 onServiceDisconnected(ComponentName componentName) {
20
21 22 };
23
24 Intent intent = new Intent(MainActivity.this,MyService.class25 bindService(intent,conn,BIND_AUTO_CREATE);开启服务
26
27 btnPlay.setOnClickListener( View.OnClickListener() {
28 29 onClick(View view) {
30 if (binder!=){
31 binder.play();
32 }
33 34 });
35 36 }
1 2 3 4 >
5 <!--enable:ture设置可用
exported:ture对外暴露 -->
7 intent-filter 8 action ="com.xqz.apppayprovider.MyService" />
9 </10 >
Button btnPay;
4 private IPay myBinder;定义AIDL
6 ServiceConnection conn = 7 @Override
10 myBinder = IPay.Stub.asInterface(iBinder);
11 }
14 17 };
18
19 21 Intent();
25 intent.setAction("com.xqz.apppayprovider.MyService"26 表示按照什么进行过滤,启动意图
27 /*android5.0之后,如果servicer不在同一个App的包中,
需要设置service所在程序的包名
29 (包名可以到App的清单文件AndroidManifest中查看)*/
30 intent.setPackage("com.xqz.apppayprovider"31 bindService(intent,1)">开启Service
32
33 btnPay = (Button) findViewById(R.id.btnPay);
34
35 btnPay.setOnClickListener(36 37 38 try {
39 myBinder.pay();
40 } catch (RemoteException e) {
41 因为是跨程序调用服务,可能会出现远程异常
42 e.printStackTrace();
43 44 45 46 47 }