Start pandora in the background from android app

1.3k Views Asked by At

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?

1

There are 1 best solutions below

0
adneal On

First glance I thought you could use Activity.startActivities, as in:

    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();
    }

But Pandora needs a little time to start playback and in that case, I think you best bet is to set up a NotificationListenerService and wait for Pandora's notification to be posted, which would indicate playback has started, then launch your app.

Here's an example:

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
    }

}

In your 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>

Also, your users will need to enable your app to listen for notifications to be posted under:

  • Settings --> Security --> Notification access

But you can direct your users straight there by using the following Intent:

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));