bindService初步了解
生活随笔
收集整理的這篇文章主要介紹了
bindService初步了解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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()取消綁定后調用該方法
轉載于:https://www.cnblogs.com/Godfunc/p/6039464.html
總結
以上是生活随笔為你收集整理的bindService初步了解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj1787
- 下一篇: 建筑施工图还有必要设计有线电视吗