通常说起activity和Service交互传递数据时,都会说用bindService的方式,用binder传递数据。
那么我下面这样做不知道可不可以:我有一个MService服务, 在MService里定义了一个instance变量,通过这个变量获取此Service的实例,像这样:public class MService extends Service {
    private static MService instance;    public MService() {
        instance = this;
    }    public static MService getInstance() {
        return instance;
    }    XXXXXXX
}这样,我不就可以不用binder什么的,直接用MService 的getInstance()方法获取实例,然后不就可以对MService进行操作了吗? 因为android Service是单例的,我试了一下,对MService的其它成员变量进行赋值获取,结果也是正常的。所以请教下,我这样做可以不可以,有什么弊端吗?

解决方案 »

  1.   

     public static MService getInstance() {
            if(instance == null){
                  instance = new MService();
            }
            return instance;
        }
      

  2.   


    谢谢补充,但是我的问题是想搞明白用这种方法来获取Service实例,然后和Serivce进行通信,是否合适……
      

  3.   


    如果想在activity里停止MService, 用stopService()的方式或者 MService.getInstance().stopSelf() 都可以吧……
      

  4.   

    可以获取,但是这样就和普通的类没什么区别了
    之所以是四大组件是因为他们的生命周期和调用是系统控制的
    比如Activity,难道我们new 一个Activity对象,在显式的调用他的onCreate等方法界面会出现吗?
    其实这么做肯定是能获取到的,如果是个小项目,随便怎么玩都可以,但是如果后期扩展项目大的话,不按照规则这么玩,麻烦可就多了
      

  5.   

    不可以  要用binder  你这种实例拿出来是没有用的,要拿到Service的对象的步骤如下
    1.在你的MService 类中添加内部类
     public class ServiceBinder extends Binder {        public MService getInstance() {
                return MService .this;
            }    }
    2.在MService 类中声明Binder对象
    private ServiceBinder mBinder;3.重写MService 类中的回调方法
    @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }4.在你的Activity中开始调用:
    private MService mService; 创建MService 对象。
    然后启动服务
     Intent bindIntent = new Intent(this, MService .class);
            bindService(bindIntent, new ServiceConnection() {
                @Override
                public void onServiceDisconnected(ComponentName name) {            }            @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((MService .ServiceBinder) service).getInstance();//程序走到这里之后,就得到了Service对象
                }
            }, BIND_AUTO_CREATE);注意在AndroidManifiest.xml中声明