Search code examples
androidandroid-activitywear-osstart-activity

Start Activity From Service When Arrived Message From Watches


I am writing an application that works with Wear OS. It is necessary that when starting the application on the watch, the application also immediately starts on the phone. The start command on the watch arrives successfully, but the application on the phone does not start. Tried launch using Intent Filters:

    if (messageEvent?.path.equals(START_ACTIVITY_ON_PHONE_PATH)) {
        val startIntent = Intent("com.example.app.gui.activities.SplashActivity")
        startIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(startIntent)
    }

In Manifest:

   <activity
        android:name="com.example.app.gui.activities.SplashActivity"
        android:noHistory="true"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.SplashActivity"
        android:windowSoftInputMode="stateHidden|stateAlwaysHidden">
        <intent-filter>
            <action android:name="com.example.app.gui.activities.SplashActivity" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Also tried using explicit call SplashActivity:

   if (messageEvent?.path.equals(START_ACTIVITY_ON_PHONE_PATH)) {
        val startIntent = Intent(this,SplashActivity::class.java)
        startIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(startIntent)
    }

Part with path is working and always see in logs:

I/Timeline: Timeline: Activity_launch_request time:3649351

Solution

  • Service which call Activity must start on foreground and set permission FOREGROUND_SERVICE manifest:

        <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    

    Service which listen event from wears:

        <service
            android:name="com.example.app.services.ListenerServiceFromWear"
            android:enabled="true"
            android:exported="true"
            android:process=":wearlistener">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
                <data
                    android:host="*"
                    android:pathPrefix="/start-activity-on-phone"
                    android:scheme="wear" />
            </intent-filter>
        </service>
    

    In receiver which start service need add:

        val startServiceIntent = Intent(context, ListenerServiceFromWear::class.java)
        context.startForegroundService(startServiceIntent)