How to call a method in activity from a service

前端 未结 4 690
失恋的感觉
失恋的感觉 2020-12-08 07:14

There is a service that listens for some voice. If voice matches a string a certain method is invoked in the service object.

public class SpeechActivationSe         


        
4条回答
  •  执笔经年
    2020-12-08 07:35

    There are many different ways to achive this. One of them to use Handler and Messanger classes. The idea of the method is to pass Handler object from Activity to Service. Every time Service wants to call some method of the Activity it just sends a Message and Activity handles it somehow.

    Activity:

    public class MyActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    showToast(msg.what);
                }
            };
    
            final Intent intent = new Intent(this, MyService.class);
            final Messenger messenger = new Messenger(handler);
    
            intent.putExtra("messenger", messenger);
            startService(intent);
        }
    
        private void showToast(int messageId) {
            Toast.makeText(this, "Message  " + messageId, Toast.LENGTH_SHORT).show();
        }
    }
    

    Service:

    public class MyService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (intent != null) {
                final Messenger messenger = (Messenger) intent.getParcelableExtra("messenger");
                final Message message = Message.obtain(null, 1234);
    
                try {
                    messenger.send(message);
                } catch (RemoteException exception) {
                    exception.printStackTrace();
                }
            }
    
            return START_NOT_STICKY;
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
    

提交回复
热议问题