服务因应用程序关闭而停止

时间:2018-07-05 13:21:05

标签: java android service

我正在开发一个墙纸应用程序,其中我在墙纸上设置了具有随机播放效果的图像图库,分别持续5分钟,10分钟等。我正在为此任务使用服务。当应用程序处于后台时,我的服务运行良好,但是当应用程序停止时,服务也停止了。这是我的服务类代码:

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

这是我用来启动服务的代码:

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

2 个答案:

答案 0 :(得分:0)

Important Fact about the bindService

如果组件调用bindService()创建服务而未调用onStartCommand(),则仅在组件绑定到该组件时,该服务才会运行。服务从其所有客户端解除绑定后,系统将销毁它。

Try using Started Service

已启动的服务是另一个组件通过调用startService()来启动的服务,这将导致对该服务的onStartCommand()方法的调用。

启动服务时,其生命周期与启动该服务的组件无关。该服务可以无限期地在后台运行,即使启动它的组件被破坏了。这样,服务应在其工作完成时通过调用stopSelf()来停止自身,否则另一个组件可以通过调用stopService()来停止它。

诸如活动之类的应用程序组件可以通过调用startService()并传递一个Intent来启动服务,该Intent指定服务并包括要使用的服务的任何数据。该服务通过onStartCommand()方法接收此Intent。

Handling onStartCommand

请注意,onStartCommand()方法必须返回一个整数。整数是一个值,它描述在系统终止服务时系统应如何继续服务。 IntentService的默认实现会为您处理此问题,但是您可以对其进行修改。 onStartCommand()的返回值必须是以下常量之一:

  1. START_NOT_STICKY 如果在onStartCommand()返回后系统终止了该服务,则除非有待交付的意向,否则不要重新创建该服务。这是最安全的选择,可以避免在不必要时以及应用程序可以简单地重新启动所有未完成的作业时运行服务。

  2. START_STICKY 如果在onStartCommand()返回后系统终止了该服务,请重新创建该服务并调用onStartCommand(),但不要重新传递最后一个意图。取而代之的是,系统将以空意图调用onStartCommand(),除非有未决的意图来启动服务。在这种情况下,这些意图就可以实现。这适用于不执行命令但无限期运行并等待任务的媒体播放器(或类似服务)。

  3. START_REDELIVER_INTENT 如果在onStartCommand()返回后系统终止了该服务,请重新创建该服务,并使用传递给该服务的最后一个意图调用onStartCommand()。任何待处理的意图都会依次传递。这适用于正在积极执行应立即恢复工作的服务,例如下载文件。

注意:在这种情况下,您应该使用启动服务,并在onStartCommand()中返回START_STICKY或START_REDELIVER_INTENT(根据您的要求)

Check Official Documentation了解服务的详细说明。

希望这会有所帮助。

答案 1 :(得分:0)

您是否已将这些行添加到清单文件中

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

相关问题