java - 为什么服务会在主进程停止时销毁?

标签 java android act

这些天我正在学习服务,只是围绕它进行试验,我无意制作音乐播放器,只是想了解服务是如何工作的。那么让我解释一下我在做什么。

我的应用程序有一个 Activity 和一个 Service 扩展 Service 我在其中的类

@Override
public void onCreate()
{
    mediaPlayer=MediaPlayer.create(this,R.raw.serenity);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    mediaPlayer.start();
    return 0;
}

在我的 MainActivity 类中,我通过

在主线程上启动 Service
startService(intent);

而且我还添加了属性

<service
        android:name=".MusicService"
        android:process=":music"/>

在另一个进程中运行服务。现在我想说的是,当我使用 Activity 类上的按钮启动服务时,服务开始播放音乐,尽管当我按下后退按钮时, Activity 被破坏并且音乐仍在播放是的,我想要什么但是当我从最近删除这个应用程序时然后音乐停止并从头开始。请告诉我为什么会这样。我不想让音乐停止,我希望它独立于应用程序的 Activity 或进程播放。

最佳答案

如果服务当前正在其 onCreate()、onStartCommand() 或 onDestroy() 方法中执行代码,则托管进程将成为前台进程,以确保这些代码可以在不被终止的情况下执行。

见:

https://developer.android.com/reference/android/app/Service.html#ServiceLifecycle

我知道这件事,但我的问题是,尽管如您所说执行 onStartCommand() 它是一个前台进程,但当我从最近的应用程序中清除该服务时,它会停止,它会停止一次并重新开始开始。 – Dushyant Suthar 14 小时前

    • 返回 START_STICKY 因为您想在关闭/崩溃时重新创建服务
    • 并使用startForeground(int,Notification);

如示例所示:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         // log start
        logger.info(getServiceName(), " Service: start id " + startId + ": " + intent);
        /** set foreground */
        setForeground();
        /** run until explicitly stopped. */
        return START_STICKY;
    }


    private setForeground() {
        Intent intent = new Intent(this, NotStickyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification noti = new, Notification.Builder(getApplicationContext())
              .setContentTitle("Pratikk")
              .setContentText("Subject")
              .setSmallIcon(R.drawable.ic_launcher)
              .setContentIntent(pendingIntent)
              .build();

       startForeground(1234, noti);     
    }
    • 不要在 list 中启用服务
    • 通过代码启动服务并使用基本上下文(不是 Activity - 因为您将得到泄漏服务的异常)
    • 您还可以提供 Binder 并绑定(bind)到 Activity 中的服务

示例启用/启动:

     /**
     * This method enables the Component (Receiver/Service) registered i
     * n the AndroidManifest file.
     */
     public static void enableComponent(Context context, Class<?> componentClass) {
        getLogger().debug("Enabling component {} request from {}", componentClass.getName(), StackTraceInfo.getInvokingClassName());

        ComponentName receiver;
        receiver = new ComponentName(context, componentClass);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

     /**
    * start a service
    *
    * @param context      - context to start service
    * @param serviceClass - service class to start
    * @return If the service is being started or is already running, the
    * {@link ComponentName} of the actual service that was started is
    * returned; else if the service does not exist null is returned.
    */
    public static ComponentName startService(Context context, Class<?> serviceClass) {
        getLogger().info("Starting service {} by {}", serviceClass.getName(), StackTraceInfo.getInvokingClassName());
        Intent serviceIntent = new Intent(context, serviceClass);
        return context.startService(serviceIntent);
    }

Yeah brother, I managed to make my service foreground so that problem is solved, but as you said and also doccumentations said that when ever system is executing onStartCommand() then it is treated as foreground but as you know when I am clearing it from recents then it is getting killed. I don't understand the difference between the system treats it as foreground and we set it as foreground why the behavior is different among both of these. – Dushyant Suthar

前台服务是一种被认为是用户主动意识到的服务,因此当内存不足时系统不会将其杀死。

前台服务必须为状态栏提供通知,该通知位于“正在进行”标题下,这意味着除非服务停止或从前景。

关于java - 为什么服务会在主进程停止时销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896636/

相关文章:

java - struts2 Web 应用程序中的 I18n 重定向问题

java - 如何解决eclipse weblogic插件jdk版本不符合错误

java - 如何判断一个jobject是LocalRef还是GlobalRef?

dbase - 如何从 ACT 读取非标准 DBF 备忘录 (BLOB) 文件?

python - 是否有可用于 ACT 的 Python 库?

java - 如何使用 Java 实体将 Bootstrap 输入类型日期持久化为 MySQL 类型日期?

java - Spring Security iusse 运行应用程序时,创建 bean myUserDetailsS​​ervice 时出错

android - 透明、无边界的 ProgressDialog

java - 在 LAN Java/Android 中查找确切的设备

.net - 为什么即使请求执行低于其限制,请求排队仍然很高?