如何检测我的应用程序是否从应用程序切换器刷过?

时间:2016-06-02 13:22:57

标签: android service android-mediaplayer

我的Android音频播放器应用程序在播放时设置绑定服务,以确保它不会被系统杀死。该应用程序使用系统媒体播放器。该服务在系统栏中创建一个通知图标。

当我从最近的应用列表中滑动应用时,该应用就会消失。但是:媒体播放器继续播放,通知保留在系统栏中。

当我选择通知或应用程序图标时,它会启动应用程序的新实例,无法访问正在运行的实例。只能通过在应用程序的系统设置中选择强制停止来停止它。如果我不从列表中滑动应用程序,我总是回到播放实例。

如果我的应用只能检测到从列表中刷出的时间,它可能会正确停止所有内容。但是不能保证调用onDestroy() - 并且不会在CM12。 onStop()或onPause()对我来说不是vadlid,因为当应用程序进入后台时音频不应该停止。

那么,如何检测从列表中刷出应用程序的时间呢?

这就是服务。可以在这做任何事吗?

public class myService extends Service {
...

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    showNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public void onDestroy() {
    mNM.cancel(NOTIFICATION);
    stopForeground(true);
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
...

private void showNotification() {
    Notification notification = new Notification(R.drawable.icon, "Hello", 0);
    Intent intent = new Intent(this, myActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "AppName", "Hello", pendIntent);
    notification.flags |= Notification.FLAG_NO_CLEAR;
    startForeground(FOREGROUNDID, notification);
    }
}

这就是我的服务的约束方式:

private static ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
          // Not used
    }

    public void onServiceDisconnected(ComponentName className) {
          // Not used
    }
};

private static void doBindService() {
    context.bindService(
        new Intent(context, myService.class),
        mConnection, Context.BIND_AUTO_CREATE);
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Service具有onTaskRemoved()方法,该方法在此方案中触发。你可以在那里停止服务:

/**
 * This is called if the service is currently running and the user has
 * removed a task that comes from the service's application.  If you have
 * set ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
 * then you will not receive this callback; instead, the service will simply
 * be stopped.
 *
 * @param rootIntent The original root Intent that was used to launch
 *                   the task that is being removed.
 */
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);

    stopSelf();
}

请记住从ServiceActivity中的onStop()解除绑定onDestroy()。 (无论什么都符合你的约束策略。)