简体   繁体   English

Android ::绑定所有活动的服务

[英]Android :: Bind Service for all activity

I want to do somethings like topic said but I have no idea what should be the step. 我想做类似主题所说的事情,但我不知道应该采取什么步骤。

I can bind service for each activity and call service methods or service call activity methods. 我可以为每个活动绑定服务,并调用服务方法或服务调用活动方法。

This is some workaround. 这是一些解决方法。 I use IBinder approach to communicate between service and activity. 我使用IBinder方法在服务和活动之间进行通信。

@Override
protected void onStart() {
    super.onStart();

    mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(Screen1.this, "Service is connected", 1000).show();
            mBounded = true;
            MqttPushService.LocalBinder mLocalBinder = (MqttPushService.LocalBinder)service;
            mService = mLocalBinder.getServerInstance();
            mService.setServiceCallbacks(Screen1.this);
            //get temp info
            try {
                mService.send("info","topic1/sensor1");
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(Screen1.this, "Service is disconnected", 1000).show();
            mBounded = false;
            mService = null;
        }
    };


    //Bind Service and Activity
    Intent mIntent = new Intent(this,MqttPushService.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);

}//END of onStart()

@Override
protected void onStop() {
    super.onStop();
    if(mBounded) {
        mService.setServiceCallbacks(null); // unregister
        unbindService(mConnection);
        mBounded = false;
    }
}//END of onStop()

However, I can't bind service to all activities in one time. 但是,我不能一次将服务绑定到所有活动。

I think of using Base Activity Class but no hope. 我想使用基本活动类,但没有希望。

I try to implement binding service in base class and let other extend this base service 我尝试在基类中实现绑定服务,然后让其他人扩展此基服务

BASECLASS 基础类

@Override
protected void onStart() {
    super.onStart();

    mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBounded = true;
            MqttPushService.LocalBinder mLocalBinder = (MqttPushService.LocalBinder)service;
            mService = mLocalBinder.getServerInstance();
            mService.setServiceCallbacks(BaseActivity.this);

            mListener.doServiceConnected();

            Toast.makeText(getBaseContext(), "Service is connected", 0).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBounded = false;
            mService = null;
            Toast.makeText(getBaseContext(), "Service is disconnected", 0).show();
        }
    };

    //Bind MQTT Service and Activity
    Intent mIntent = new Intent(this,MqttPushService.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();

    if(mBounded) {
        mService.setServiceCallbacks(null); // unregister
        unbindService(mConnection);
        mBounded = false;
    }
}

@Override
public void doSomething(String act) {
    mListener.doServiceReturn(act);
}

protected void setServiceAttachedListener(onServiceAttached listener) {
    mListener = listener;
}

public interface onServiceAttached{
    void doServiceConnected();
    void doServiceReturn(String act);
}

When Screen1.class (First Activity) set callbacks methods 当Screen1.class(第一个活动)设置回调方法时

  1. call service method and do some task 呼叫服务方法并执行一些任务
  2. listen for returning resul and do some task 聆听返回的resul并执行一些任务

There is no problem in this class but when I intent and new screen(SleepMode.class) which is implementation like this class but service Log.d me that null of serviceCallBacks. 在这个类中没有问题,但是当我打算创建一个新的screen(SleepMode.class)时,它是类似于该类的实现,但是服务Log.d我是serviceCallBacks的null。 when service want to call activity methods. 服务何时要调用活动方法。

public class Screen1 extends BaseActivity implements BaseActivity.onServiceAttached  {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = inflater.inflate(R.layout.main, null, false);
    mDrawer.addView(contentView, 0);

    setServiceAttachedListener(Screen1.this);
}

@Override
public void doServiceConnected() {

    try {
        mService.send("info","topic1/sensor1");
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

@Override
public void doServiceReturn(String act) {
    if (act.equals("SCREEN1")) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateCurrentFragment();
            }
        });
    }
}

} }

FINALLY 最后

My goal is I want to bind service with all activity. 我的目标是我想将服务与所有活动绑定在一起。 Also, service and activity should be able to talk with each other.. Is it possible ?? 此外,服务和活动应该能够互相交谈。是否可能? Please advice me some approach thx. 请告诉我一些方法。

NOTE 注意

I TRY to summarize my question but I don't know where to start. 我尝试总结我的问题,但我不知道从哪里开始。

I TRY to show some work around and want to tell what happen. 我尝试展示一些解决方法,并想告诉您发生了什么。

Sorry to make it a bit long long question. 很抱歉让这个问题有点漫长。

First of all, your Service isn't the one that binds to activities, your Service is the component that is doing some operation and your activities are the ones that bind to the service in order to get data from it or something. 首先,您的Service不是绑定到活动的Service ,您的Service是进行某些操作的组件,您的活动是绑定到服务以从中获取数据或某些东西的活动。

So you need to bind to your service every time you open a new activity, your approach of having a base activity that binds to the service in its onCreate is pretty good. 因此,每次打开新活动时,您都需要绑定到服务,因此在onCreate中具有将基本活动绑定到服务的方法非常好。

and then you can have interfaces that your service implement so you can communicate with your service, and have some callbacks so your activity is notified when your service need to communicate back to activity. 然后您可以拥有服务实现的接口,以便可以与服务进行通信,并具有一些回调,以便在服务需要与活动进行通信时通知您的活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM