簡體   English   中英

服務在應用程序關閉時停止

[英]Service get stopped on app closing

我正在開發一個牆紙應用程序,在該應用程序中,我在牆紙上設置了一個具有 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);

關於 bindService 的重要事實

如果組件調用 bindService() 來創建服務並且未調用 onStartCommand(),則服務僅在組件綁定到它時運行。 在服務與其所有客戶端解除綁定后,系統將其銷毀。

嘗試使用已啟動的服務

啟動的服務是另一個組件通過調用 startService() 啟動的服務,這會導致調用服務的 onStartCommand() 方法。

當服務啟動時,它的生命周期獨立於啟動它的組件。 該服務可以無限期地在后台運行,即使啟動它的組件已被銷毀。 因此,服務應該在其作業完成時通過調用 stopSelf() 自行停止,或者另一個組件可以通過調用 stopService() 來停止它。

應用程序組件(如活動)可以通過調用 startService() 並傳遞指定服務並包含服務要使用的任何數據的 Intent 來啟動服務。 服務在 onStartCommand() 方法中接收此 Intent。

處理 onStartCommand

注意 onStartCommand() 方法必須返回一個整數。 整數是一個值,描述了在系統終止服務的情況下系統應如何繼續服務。 IntentService 的默認實現會為您處理此問題,但您可以對其進行修改。 onStartCommand() 的返回值必須是以下常量之一:

  1. START_NOT_STICKY如果系統在 onStartCommand() 返回后終止服務,除非有待交付的意圖,否則不要重新創建服務。 這是最安全的選擇,可以避免在不需要時運行服務,並且當您的應用程序可以簡單地重新啟動任何未完成的作業時。

  2. START_STICKY如果系統在 onStartCommand() 返回后終止服務,則重新創建服務並調用 onStartCommand(),但不要重新傳遞最后一個意圖。 相反,系統會以空意圖調用 onStartCommand() ,除非有待啟動的意圖來啟動服務。 在這種情況下,這些意圖就會被傳遞。 這適用於不執行命令但無限期運行並等待作業的媒體播放器(或類似服務)。

  3. START_REDELIVER_INTENT如果系統在 onStartCommand() 返回后終止服務,則重新創建服務並使用傳遞給服務的最后一個意圖調用 onStartCommand()。 依次傳遞任何未決意圖。 這適用於正在積極執行應立即恢復的作業的服務,例如下載文件。

注意:在您的情況下,您應該使用 Started Service 並在 onStartCommand() 中返回 START_STICKY 或 START_REDELIVER_INTENT (根據您的要求)

有關服務的詳細說明, 請查看官方文檔

您是否在清單文件中添加了這些行

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM