0

I have an android application that starts pandora by voice command. It works great, but I want the activity to switch back to my application, leaving pandora running in the background. I'm using this code to launch pandora:

PackageManager pm = getPackageManager()
   try{
       String packageName = "com.pandora.android";
       launchIntent = pm.getLaunchIntentForPackage(packageName);

       startActivity(launchIntent);
      }
   catch (Exception e1)
   {}

Any thoughts?

4

1 回答 1

0

乍一看,我认为您可以使用Activity.startActivities,如:

    final PackageManager pm = getPackageManager();
    try {
        startActivities(new Intent[] {
                pm.getLaunchIntentForPackage("com.pandora.android"),
                pm.getLaunchIntentForPackage("com.your.packagename")
        });
    } catch (final Exception ignored) {
        // Nothing to do
    } finally {
        finish();
    }

但是 Pandora 需要一点时间来开始播放,在这种情况下,我认为你最好的办法是设置一个NotificationListenerService并等待 Pandora 的通知发布,这表明播放已经开始,然后启动你的应用程序。

这是一个例子:

public class PandoraNotificationListener extends NotificationListenerService {

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        final String packageName = sbn.getPackageName();
        if (!TextUtils.isEmpty(packageName) && packageName.equals("com.pandora.android")) {
            startActivity(new Intent(this, YourActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        // Nothing to do
    }

}

在您的 AndroidManifest 中

<service
    android:name="your.path.to.PandoraNotificationListener"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

此外,您的用户将需要启用您的应用程序以侦听要在以下位置发布的通知:

  • 设置 --> 安全 --> 通知访问

但是您可以使用以下命令直接将您的用户引导到那里Intent

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
于 2014-04-17T02:55:41.813 回答