Search code examples
javaandroidwear-osandroid-wear-data-api

Executeing a method in Handheld class from Wear Module Android


Let's say I have a Method in MainActivity called Emergencyalert(), what it dose is, it sends some alert message to some selected contacts. So I wanted a wear app which dose nothing but just execute the Emergencyalert() Method in Handheld Device, When the user click on a Emergency button in Android Wear. There are two different modules in my project called mobile and wear. I use AndroidStudio. Advance Thanks.


Solution

  • First move your Emergencyalert() method into a service (an IntentService would be perfect for this: just have your Emergencyalert() code run in the service's onHandleIntent()). This is necessary since methods in your activity can only be called when your activity is open and visible on screen (which wouldn't be the case when activated via your Wear app).

    You can test to make sure your IntentService is working by replacing your call to Emergencyalert() in your MainActivity with a call to

    startService(new Intent(MainActivity.this, EmergencyAlertIntentService.class));
    

    This will start the service and do your emergency alert.

    For the Android Wear portion, your Wear app needs to send a Message to your handheld device, stating that the emergency button was pressed. You should then implement a WearableListenerService in your handheld app and override the onMessageReceived() method - in that method, call the same startService() you called in your MainActivity and your emergency alert will fire even when your app is in the background when you hit the button on the Android Wear device.