Operation UI in service

In the development process, you need to load a view in the service, and you can send a request to the service to change the view display in any page. Because the UI operation cannot be performed in the non main thread, and the view related data is in the service, you must use other methods to operate the UI.

Radio broadcast

Customize a broadcast inheritor within service

class FloatWindowBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //IntentFilter identity
            if (ACTION_FLOAT.equals(action)){
                //Transmit data
                String command = intent.getStringExtra("command");
                int position = intent.getIntExtra("position",0);
                switch (command){
                    case test:
                         break;
                    default:
                        ToastUtil.showMessage("Parameter error");
                        break;
                }

            }
        }
    }

Initialize, add identity, register broadcast.

private FloatWindowBroadcastReceiver floatWindowBroadcastReceiver;
@Override
    public void onCreate() {
        super.onCreate();
       //Initialization
        floatWindowBroadcastReceiver = new FloatWindowBroadcastReceiver();
       //Identification
        IntentFilter filter = new IntentFilter(ACTION_FLOAT);
       //Registered broadcasting
        registerReceiver(floatWindowBroadcastReceiver,filter);       
    }

Unregister broadcast when service is destroyed

@Override
    public void onDestroy() {
        if (floatWindowBroadcastReceiver != null){
            unregisterReceiver(floatWindowBroadcastReceiver);
            floatWindowBroadcastReceiver = null;
        }
        super.onDestroy();
    }

Call the method action in another page

Intent intent=new Intent(FloatWindowService.ACTION_FLOAT);
intent.putExtra("command","add");
sendBroadcast(intent);

Handler

Create a Handler in service to receive messages

private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){

            }
        }
 };

Send message, whether it is necessary to enable thread to operate according to requirements

 public void send(){
     new Thread(new Runnable() {
          @Override
          public void run() {
          Message message=new Message();
          Bundle bundle=new Bundle();
          message.setData(bundle);
          handler.sendMessageDelayed(message,2000);
    }).start();

 } 

Added by thyscorpion on Fri, 27 Mar 2020 18:40:02 +0200