文章出處

bindService的使用:

    當需要調Service里面的方法時,可以用bindService()

首先定義一個類繼承于Service,然后配置Manifest.xml文件

 1 public class MyBindService extends Service {
 2     @Nullable
 3     @Override
 4     public IBinder onBind(Intent intent) {
 5         return new MyBinder();
 6     }
 7     public void myfunction(){
 8         System.out.println("我是服務里的方法");
 9     }
10     @Override
11     public void onCreate() {
12         super.onCreate();
13     }
14     public class MyBinder extends Binder{
15         public void call(){
16             myfunction();
17         }
18     }
19 }

 

通過onBind()方法返回一個對象,給onServiceConnected(ComponentName name, IBinder service)

方法里面的Service,然后通過強轉得到一個MyBinder對象

myBinder = (MyBindService.MyBinder)service;
用myBinder對象調用call方法,從而調到服務里面的myfunction()方法

 1 public class MainActivity extends AppCompatActivity {
 2 
 3     private Myconn conn;
 4     private MyBindService.MyBinder myBinder;
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_main);
10     }
11 
12     public void click(View v){
13         conn = new Myconn();
14         bindService(new Intent(this,MyBindService.class),conn,BIND_AUTO_CREATE);
15     }
16 
17     public void click1(View v){
18         myBinder.call();
19     }
20     public void click2(View v){
21         unbindService(conn);
22     }
23 
24     private class Myconn implements ServiceConnection {
25         @Override
26         public void onServiceConnected(ComponentName name, IBinder service) {
27             myBinder = (MyBindService.MyBinder)service;
28         }
29         @Override
30         public void onServiceDisconnected(ComponentName name) {
31         }
32     }
33 }
onServiceConnected()當綁定成功后調用該方法。
onServiceDisconnected()取消綁定后調用該方法

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()