调用服务中的方法

服务中的方法不能通过直接 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);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容