Android bindservice使用

 1 package com.example.myact10;
 2 
 3 import com.example.myact10.MyService.MyBinder;
 4 
 5 import android.support.v7.app.ActionBarActivity;
 6 import android.content.ComponentName;
 7 import android.content.Intent;
 8 import android.content.ServiceConnection;
 9 import android.os.Bundle;
10 import android.os.IBinder;
11 import android.util.Log;
12 import android.view.View;
13 import android.widget.Button;
14 /**
15  * Android bindService实现Activity和service的绑定
16  * @Describe: 
17  * @package: com.example.myact10
18  * @author shaobn
19  * @date 2015-9-15 下午2:25:52
20  */
21 public class MainActivity extends ActionBarActivity {
22     private Button myButton;
23     @Override
24     protected void onCreate(Bundle savedInstanceState) {
25         super.onCreate(savedInstanceState);
26         setContentView(R.layout.activity_main);
27         myButton = (Button) this.findViewById(R.id.button1);
28         myButton.setOnClickListener(new View.OnClickListener() {
29             
30             @Override
31             public void onClick(View arg0) {
32                 // TODO Auto-generated method stub
33                 ServiceConnection serviceConnection = new ServiceConnection() {
34                     
35                     @Override
36                     public void onServiceDisconnected(ComponentName arg0) {
37                         // TODO Auto-generated method stub
38                     }
39                     
40                     @Override
41                     public void onServiceConnected(ComponentName arg0, IBinder inBinder) {
42                         // TODO Auto-generated method stub
43                         MyBinder myBinder = (MyBinder)inBinder;
44                         Log.i("String",myBinder.getData());
45                     }
46                 };
47                 Intent intent = new Intent();
48                 intent.setClass(MainActivity.this,MyService.class);
49                 bindService(intent, serviceConnection,BIND_AUTO_CREATE);
50             }
51         });
52     }
53     
54 }
 1 package com.example.myact10;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.os.Binder;
 6 import android.os.IBinder;
 7 
 8 public class MyService extends Service {
 9     @Override
10     public void onCreate() {
11         // TODO Auto-generated method stub
12         super.onCreate();
13     }
14     @Override
15     public IBinder onBind(Intent intent) {
16         // TODO Auto-generated method stub
17         MyBinder myBinder = new MyBinder();
18         return myBinder;
19     }
20     public class MyBinder extends Binder{
21         public String getData(){
22             
23             return "onBind Service";
24         }
25         
26     }
27 
28 }
原文地址:https://www.cnblogs.com/assassin666/p/4810198.html