调用服务中的方法

作者: 上行彩虹人 | 来源:发表于2017-08-07 10:46 被阅读19次

    服务中的方法不能通过直接 new对象的方法调用,必须通过ibinder作为中间人调用

    1、定义服务类

    public class methodService extends Service
    

    2、定义测试的方法

        //定义测试的方法
        public void tsxtMethod(){
            Toast.makeText(getApplicationContext(),"我是服务中的方法。。。", Toast.LENGTH_LONG).show();
        }
    

    3、定义中间人调用tsxtMethod方法 myBinder是内部

    //定义中间人调用tsxtMethod方法
        //Binder是ibinder的直接子类
        public class myBinder extends Binder{
            //调用服务的的方法
            public void callTsxtMethod(){
              tsxtMethod();
          }
        }
    

    4、返回myBinder

      @Override
        public IBinder onBind(Intent intent) {
           // return null;
            // 返回myBinder
            return new myBinder();
        }
    

    5、main函数

    public class MainActivity extends AppCompatActivity {
        methodService.myBinder mybinder;
        Mycon mycon;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //开启服务
            Intent intent = new Intent(this, methodService.class);
            mycon = new Mycon();
            bindService(intent,mycon,BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onDestroy() {
            //服务被销毁时解绑服务
            unbindService(mycon);
            super.onDestroy();
        }
        //点击按钮调用服务的方法
        public void click(View V){
            mybinder.callTsxtMethod();
        }
        private class Mycon implements ServiceConnection{
            //服务连接成功被调用
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
               //获取中间人对象
                mybinder = (methodService.myBinder) service;
            }
            //服务连接取消被调用
            @Override
            public void onServiceDisconnected(ComponentName name) {
    
            }
        }
    }
    

    注:某些场合需要StartService和bindservice混合方式开启服务。即既需要调用服务中的方法也需要让服务在后台长期运行(如音乐播放器的案例)。需要先调用StartService方法开启服务,在调用bindservice,使用unbindService解绑。

    //混合方式启动Service
            Intent intent = new Intent(this,MusicService.class);
            startService(intent);
            myConn = new MyConn();
            bindService(intent,myConn,BIND_AUTO_CREATE);
    

    相关文章

      网友评论

        本文标题:调用服务中的方法

        本文链接:https://www.haomeiwen.com/subject/mkmolxtx.html