为什么主进程停止时服务会被破坏?

时间:2016-06-18 11:55:46

标签: 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"/>

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

2 个答案:

答案 0 :(得分:2)

如果服务当前正在其onCreate(),onStartCommand()或onDestroy()方法中执行代码,那么托管进程将是一个前台进程,以确保此代码可以执行而不会被杀死。

请参阅:

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

我知道这件事,但我的问题是,虽然当你说执行onStartCommand()时它是一个前台进程,当我从最近清除应用程序时,它会停止一次停止的服务并再次启动开始。 - Dushyant Suthar 14小时前

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

        @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);     
        }
    
      • 不启用清单中的服务
      • 通过代码&amp; amp;使用基本上下文(不是活动 - 因为你会得到泄漏服务的例外)
      • 你也可以提供活页夹&amp;从活动绑定到服务
    1. 示例启用/启动:

           /**
           * 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);
          }
      
        

      是的兄弟,我设法使我的服务前景如此问题得到解决,但正如你所说的那样,doccumentations说当系统执行onStartCommand()时它被视为前景但你知道什么时候我从最近清理它然后它被杀死了。我不理解系统将其视为前景之间的差异,我们将其设置为前景,为什么这两者之间的行为不同。 - Dushyant Suthar

      前台服务是一种被认为是用户主动了解的服务,因此在内存不足时不会杀死系统。

      前台服务必须为状态栏提供通知,该状态栏位于&#34;正在进行的&#34;标题,这意味着除非服务被停止或从前台删除,否则不能解除通知。

答案 1 :(得分:0)

为了使您的服务更稳定,您应该创建一个前台服务。每次主进程停止时,这都不会终止服务。我遇到了类似的问题,在我的进程中,当我停止主进程时,我的进程被杀死并重新启动。为了避免这种情况,我使用了前台服务。以下链接可让您轻松实现和了解前台进程。希望这可以帮助。 Android-foreground service example

相关问题