如何从可穿戴设备中打开主应用程序?

7
我正在尝试使用可穿戴设备,已经创建了一些来自微应用程序(运行在可穿戴设备上)的通知(有一些限制),现在想知道如何创建一个待定意图以便打开手机上的主应用程序。
2个回答

6

我不知道是否还有其他方法。

然而它可以起作用。 在您的wear模块中建立一个通知,启动 wear 中的广播。 广播(在 wear 上运行)使用 Message.API 向移动模块发送消息。 在移动模块上,存在一个 WearableListenerService,会启动移动设备上的 MainActivity。

在您的Wear中构建通知:

 // Notification
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                                //.setContentTitle(mNotificationUtil.getTitle())
                        .setContentText("Text")
                        .setContentIntent(getPendingIntent(this));

        // Get an instance of the NotificationManager service
        NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(this);

        // Build the notification and issues it with notification manager.
        notificationManager.notify(1, notificationBuilder.build());

    }

    private PendingIntent getPendingIntent(MainActivity mainActivity) {
        final String INTENT_ACTION = "it.gmariotti.receiver.intent.action.TEST";

        Intent intent = new Intent();
        intent.setAction(INTENT_ACTION);
        PendingIntent pendingIntent =
                PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        return pendingIntent;
    }

这个通知会发出一个广播消息。 请在wear/AndroidManifest.xml中声明此广播。
<meta-data android:name="com.google.android.gms.version" 
          android:value="@integer/google_play_services_version" />


 <receiver android:name=".MyBroadcast">
         <intent-filter>
              <action android:name="it.gmariotti.receiver.intent.action.TEST"/>
         </intent-filter>
 </receiver>

然后实现广播以发送消息:
public class MyBroadcast extends BroadcastReceiver implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    Node mNode; // the connected device to send the message to
    GoogleApiClient mGoogleApiClient;
    private static final String WEAR_PATH = "/hello-world-wear";

    @Override
    public void onReceive(Context context, Intent intent) {

        //Connect the GoogleApiClient
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mGoogleApiClient.connect();
    }
    /**
     * Send message to mobile handheld
     */
    private void sendMessage() {

        if (mNode != null && mGoogleApiClient!=null && mGoogleApiClient.isConnected()) {
            Wearable.MessageApi.sendMessage(
                    mGoogleApiClient, mNode.getId(), WEAR_PATH, null).setResultCallback(

                    new ResultCallback<MessageApi.SendMessageResult>() {
                        @Override
                        public void onResult(MessageApi.SendMessageResult sendMessageResult) {

                            if (!sendMessageResult.getStatus().isSuccess()) {
                                Log.e("TAG", "Failed to send message with status code: "
                                        + sendMessageResult.getStatus().getStatusCode());
                            }
                        }
                    }
            );
        }else{
            //Improve your code
        }

    }

    /*
     * Resolve the node = the connected device to send the message to
     */
    private void resolveNode() {

        Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
            @Override
            public void onResult(NodeApi.GetConnectedNodesResult nodes) {
                for (Node node : nodes.getNodes()) {
                    mNode = node;
                }
                sendMessage();
            }
        });
    }


    @Override
    public void onConnected(Bundle bundle) {
        resolveNode();
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Improve your code
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //Improve your code
    }
}

这段代码将会发送一条信息到你的手机,需要在你的wear/build.gradle文件中进行配置。

dependencies {
    compile "com.google.android.support:wearable:1.0.+"
    compile 'com.google.android.gms:play-services-wearable:+'
}

在移动模块上,您需要实现一个WearableListenerService
/**
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class ListenerServiceFromWear extends WearableListenerService {

    private static final String WEAR_PATH = "/hello-world-wear";

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {

        /*
         * Receive the message from wear
         */
        if (messageEvent.getPath().equals(WEAR_PATH)) {

            Intent startIntent = new Intent(this, MainActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startIntent);
        }    
    }    
}

在你的Mobile/AndroidManifest.xml文件中,需要声明该服务。

<service android:name=".ListenerServiceFromWear">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>

还有这个mobile/build.gradle依赖项:

dependencies {
    wearApp project(':wear')
    compile 'com.google.android.gms:play-services-wearable:+'
}

这怎么可能呢?我无法从可穿戴设备访问MainActivity类,因为它是不同的apk文件。 - rekire
你可以在手机应用程序中创建通知。 你是否只在可穿戴应用程序中创建通知? - Gabriele Mariotti
是的,在这种特殊情况下,我正在谈论为可穿戴设备创建通知,并在可穿戴设备上进行。 - rekire
那我也可以在手机上实现一个 WearableListenerService 吗?我对这一点不太确定。 - rekire
那会很好,但我相信有一些特殊的意图可以自动完成这个操作。我认为我需要挂钩可穿戴设备上的通知来获取我想要的意图。 - rekire
显示剩余2条评论

3

我刚测试过的解决方案是在安卓应用程序上添加一个消息监听器,然后从可穿戴设备发送我想要执行的详细信息即可。

public class WearMessagesAPI_Service
        extends WearableListenerService {


    private static final String OPEN_APP_PATH = "/OpenApp";

    @Override
    public void onMessageReceived(MessageEvent event) {
        Log.w("WearMessagesAPI_Service", event.getPath());
        String activityKey = new String(event.getData());
        if(activityKey.equals(...)) {
            Intent myAppIntent = ... create intent ...
            startActivity(myAppIntent);
        }
    }
}

别忘了将其添加到你的清单文件(manifest)中:

<service android:name=".wearable.WearMessagesAPI_Service">
    <intent-filter>
        <action android:name="com.google.android.gms.wearable.BIND_LISTENER"/>
    </intent-filter>
</service>

我相信这就是全部内容了。 让我知道进展如何 :)


啊,我现在想起来我的问题了。WearableListenerService是Play服务可穿戴库的一部分。你确定它可以在普通手机上使用吗?好吧,minSdkVersion是9,所以可能可以工作。 - rekire
最低API 20是在可穿戴设备上运行可穿戴设备的要求。如果您使用包括一些可穿戴类的com.google.android.gms:play-services:6.1.71库,则可以在手机应用程序中使用WearableListenerService。 - TacB0sS
@TacB0sS,你有示例项目吗?我在代码方面遇到了麻烦。这个条件应该是什么?activityKey.equals(...) - Jack Shultz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接