简体   繁体   English

服务在应用程序关闭时停止

[英]Service get stopped on app closing

I am working on a wallpaper application in which i am setting a gallery of images on wallpaper with shuffle effect for 5 min, 10 min etc. I am using service for this task.我正在开发一个墙纸应用程序,在该应用程序中,我在墙纸上设置了一个具有 5 分钟、10 分钟等随机播放效果的图像库。我正在为这项任务使用服务。 My service works well when app remains in background, but service get stopped when app get stopped.This is my code for service class:当应用程序保持在后台时,我的服务运行良好,但是当应用程序停止时服务停止。这是我的服务类代码:

public class WallpaperService extends Service {
ArrayList<String> arrayList;int counter = 0;

boolean serviceStopped;

private IBinder binder = new WallpaperServiceBinder();

public WallpaperService() {
}

private Handler mHandler;

private Runnable updateRunnable = new Runnable() {
    @Override
    public void run() {
        if (serviceStopped == false)
        {
            createNotificationIcon();
        }
        queueRunnable();
    }
};

public class WallpaperServiceBinder extends Binder {
    public WallpaperService getService() {
        return WallpaperService.this;
    }
}

private void queueRunnable() {
    // 600000 : cada 10 minutos, comprueba si hay nuevas notificaciones y actualiza la
    // notification BAR
    mHandler.postDelayed(updateRunnable, 5000);
}

@Override
public int onStartCommand(Intent intent,int flag, int start_id){
    super.onStartCommand(intent,flag,start_id);
    arrayList = intent.getStringArrayListExtra("image_url");
    return START_STICKY;
}

@Override
public void onRebind(Intent intent) {
    Log.v("Service","in onRebind");
    super.onRebind(intent);
}

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

@Override
public void onCreate() {
    serviceStopped = false;
    mHandler = new Handler();
    queueRunnable();
}

@Override
public void onStart(Intent intent, int startid) {

}

public void createNotificationIcon()
{
    counter += 1;
    Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
    Picasso.with(getApplicationContext()).load(arrayList.get(counter)).into(new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            try {
                final WallpaperManager wallpaperManager =
                        WallpaperManager.getInstance(getApplicationContext());
                wallpaperManager.setBitmap(bitmap);
                wallpaperManager.suggestDesiredDimensions(1080, 1920);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            //Here you should place a loading gif in the ImageView to
            //while image is being obtained.
        }
    });
}}

This is the code i am using to start service:这是我用来启动服务的代码:

Intent intent = new Intent(CategoryActivity.this,WallpaperService.class);
            intent.putExtra("image_url",img_urls);
            intent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
            startService(intent);
            bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);

Important Fact about the bindService 关于 bindService 的重要事实

If a component calls bindService() to create the service and onStartCommand() is not called, the service runs only as long as the component is bound to it.如果组件调用 bindService() 来创建服务并且未调用 onStartCommand(),则服务仅在组件绑定到它时运行。 After the service is unbound from all of its clients, the system destroys it.在服务与其所有客户端解除绑定后,系统将其销毁。

Try using Started Service 尝试使用已启动的服务

A started service is one that another component starts by calling startService(), which results in a call to the service's onStartCommand() method.启动的服务是另一个组件通过调用 startService() 启动的服务,这会导致调用服务的 onStartCommand() 方法。

When a service is started, it has a lifecycle that's independent of the component that started it.当服务启动时,它的生命周期独立于启动它的组件。 The service can run in the background indefinitely, even if the component that started it is destroyed.该服务可以无限期地在后台运行,即使启动它的组件已被销毁。 As such, the service should stop itself when its job is complete by calling stopSelf(), or another component can stop it by calling stopService().因此,服务应该在其作业完成时通过调用 stopSelf() 自行停止,或者另一个组件可以通过调用 stopService() 来停止它。

An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use.应用程序组件(如活动)可以通过调用 startService() 并传递指定服务并包含服务要使用的任何数据的 Intent 来启动服务。 The service receives this Intent in the onStartCommand() method.服务在 onStartCommand() 方法中接收此 Intent。

Handling onStartCommand 处理 onStartCommand

Notice that the onStartCommand() method must return an integer.注意 onStartCommand() 方法必须返回一个整数。 The integer is a value that describes how the system should continue the service in the event that the system kills it.整数是一个值,描述了在系统终止服务的情况下系统应如何继续服务。 The default implementation for IntentService handles this for you, but you are able to modify it. IntentService 的默认实现会为您处理此问题,但您可以对其进行修改。 The return value from onStartCommand() must be one of the following constants: onStartCommand() 的返回值必须是以下常量之一:

  1. START_NOT_STICKY If the system kills the service after onStartCommand() returns, do not recreate the service unless there are pending intents to deliver. START_NOT_STICKY如果系统在 onStartCommand() 返回后终止服务,除非有待交付的意图,否则不要重新创建服务。 This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.这是最安全的选择,可以避免在不需要时运行服务,并且当您的应用程序可以简单地重新启动任何未完成的作业时。

  2. START_STICKY If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent. START_STICKY如果系统在 onStartCommand() 返回后终止服务,则重新创建服务并调用 onStartCommand(),但不要重新传递最后一个意图。 Instead, the system calls onStartCommand() with a null intent unless there are pending intents to start the service.相反,系统会以空意图调用 onStartCommand() ,除非有待启动的意图来启动服务。 In that case, those intents are delivered.在这种情况下,这些意图就会被传递。 This is suitable for media players (or similar services) that are not executing commands but are running indefinitely and waiting for a job.这适用于不执行命令但无限期运行并等待作业的媒体播放器(或类似服务)。

  3. START_REDELIVER_INTENT If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service. START_REDELIVER_INTENT如果系统在 onStartCommand() 返回后终止服务,则重新创建服务并使用传递给服务的最后一个意图调用 onStartCommand()。 Any pending intents are delivered in turn.依次传递任何未决意图。 This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.这适用于正在积极执行应立即恢复的作业的服务,例如下载文件。

Note: In your case you should use Started Service and return START_STICKY or START_REDELIVER_INTENT (based on your requirement) in onStartCommand()注意:在您的情况下,您应该使用 Started Service 并在 onStartCommand() 中返回 START_STICKY 或 START_REDELIVER_INTENT (根据您的要求)

Check Official Documentation for detailed description of the Services.有关服务的详细说明, 请查看官方文档

您是否在清单文件中添加了这些行

<application> <service  android:name=".ExampleService" /></application>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使应用程序被强制停止,也要重新启动服务,即使关闭应用程序,也要在后台继续运行服务如何? - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? 即使应用程序被强制停止,也要重新启动服务;关闭应用程序后,仍要在后台运行服务。 - Restart the service even if app is force-stopped and Keep running service in background even after closing the app How? Service App停止工作 - Service App stopped working 关闭应用程序后服务未运行 - Service not running after closing app 关闭应用程序后服务停止运行 - Service stops running after closing the app 关闭应用程序后如何停止意图服务 - How to stop intent service after closing app 关闭应用程序并且服务仍在运行后的NullPointerException - NullPointerException after Closing App with Service still running 当应用程序从android中的最新应用程序列表中删除时,服务停止 - Service stopped when the app removes from recent apps list in android 从Android中的最新应用中刷出应用后,服务停止 - Service stopped when app is swiped out from recent apps in Android 当我调用第二个活动(主)时,应用停止运行 - App get stopped when I call second Activity (Main)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM