简体   繁体   English

ASyncTask分离完成后如何结束android服务?

[英]How to end android service after ASyncTask it spun off completes?

I have a Downloader Service that loads a list of downloads to run from my database. 我有一个Downloader Service,它可以下载要从我的数据库运行的下载列表。

It then creates an ASyncTask that will run the downloads in a background Thread. 然后,它创建一个ASyncTask,它将在后台线程中运行下载。

This all works perfectly well, but the problem is I don't currently have a way to tell the service that the Downloader has completed. 一切都很好,但是问题是我目前还没有办法告诉服务下载程序已完成。 I somehow have to send the service a message from the ASyncTask's onPostExecute function (which runs on the UIThread). 我必须以某种方式通过ASyncTask的onPostExecute函数(在UIThread上运行)向服务发送消息。

I can't simply close the service remotely because the Service has some work to do when the ASyncTask completes. 我不能简单地远程关闭该服务,因为当ASyncTask完成时,该服务还有一些工作要做。

I've considered registering a listener from the service and calling it in onPostExecute, but I think this would cause problems like closing the service before the Task was complete or some threadlocking issues. 我已经考虑过从服务中注册一个侦听器,并在onPostExecute中对其进行调用,但是我认为这将导致诸如在Task完成之前关闭服务之类的问题或某些线程锁定问题。

How can I send a message (like a broadcast intent) to my Downloader service from my ASyncTask? 如何从ASyncTask向下载器服务发送消息(如广播意图)?

EDIT 编辑
Here's some code for those of you confused about what I am doing. 这是一些让我感到困惑的代码。

DownloadService.java (Important bits): DownloadService.java(重要位):

public class DownloadService extends Service implements OnProgressListener {

/** The Downloads. */
private List<Download> mDownloads = new ArrayList<Download>(10);

private DownloadTask mDownloadTask;

/** The Intent receiver that handles broadcasts. */
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent) {
        DebugLog.i(TAG, "onRecieve" +intent.toString());
        handleCommand(intent);
    }

};

/* (non-Javadoc)
 * @see android.app.Service#onCreate()
 */
@Override
public void onCreate() {
    DebugLog.i(TAG, "onCreate");
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(ACTION_PAUSE_DOWNLOADS);
    commandFilter.addAction(ACTION_START_DOWNLOADS);
    registerReceiver(mIntentReceiver, commandFilter);
}

/* (non-Javadoc)
 * @see android.app.Service#onDestroy()
 */
@Override
public void onDestroy(){
    DebugLog.i(TAG, "onDestroy");
    //Make sure all downloads are saved and stopped
    pauseAllDownloads();
    //unregister command receiver
    unregisterReceiver(mIntentReceiver);
    //cancel notifications
    closeNotification();
}

/* (non-Javadoc)
 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
 */a
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}
/**
 * Handle command sent via intent.
 * <strong>Warning, this function shouldn't do any heavy lifting.  
 * This will be run in UI thread and should spin off ASyncTasks to do work.</strong>
 *
 * @param intent the intent
 */
private void handleCommand(Intent intent) {
    if(intent != null){
        String action = intent.getAction();
        Uri data = intent.getData();
        if(action.equals(ACTION_START_DOWNLOADS))
        {
            updateDownloads();//Fetch list of downloads to do from database
            startDownloads();//run downloads
        }else if(action.equals(ACTION_PAUSE_DOWNLOADS)){
            pauseAllDownloads();
        }
    }
}

/**
 * Start all downloads currently in list (in order).
 */
private void startDownloads()
{
    pauseAllDownloads();//make sure we don't have a download task running
    mDownloadTask = new DownloadTask();
    mDownloadTask.setOnProgressListener(this);
    Download[] downloads = new Download[mDownloads.size()];
    for(int i = 0; i<mDownloads.size(); i++)
    {
        Download d = mDownloads.get(i);
        if(d.getStatus() != Download.COMPLETE)
        {
            downloads[i] = mDownloads.get(i);   
        }
    }
    //must be called on UI thread
    mDownloadTask.execute(downloads);
}

/**
 * Pause downloads.
 */
private void pauseAllDownloads()
{
    if(mDownloadTask == null)
    {
        //Done.  Nothing is downloading.
        return;
    }

    //Cancel download task first so that it doesn't start downloading next
    if(mDownloadTask.cancel(true))
    {
        //Task has been canceled.  Pause the active download.
        Download activeDownload = mDownloadTask.getActiveDownload();
        if(activeDownload != null)
        {
            activeDownload.pause();
        }
    }else
    {
        if(mDownloadTask.getStatus() == AsyncTask.Status.FINISHED)
        {
            DebugLog.w(TAG, "Download Task Already Finished");
        }else{
            //Task could not be stopped
            DebugLog.w(TAG, "Download Task Could Not Be Stopped");
        }
    }
}

@Override
public void onProgress(Download download) {
    //download progress is reported here from DownloadTask
}
}

DownloadTask: 下载任务:

/**
 * The Class DownloadTask.
 */
public class DownloadTask extends AsyncTask<Download, Download, Void> {

/** The On progress listener. */
private OnProgressListener mOnProgressListener;

/**
 * The listener interface for receiving onProgress events.
 * The class that is interested in processing a onProgress
 * event implements this interface and registers it with the component.
 *
 */
public static interface OnProgressListener
{

    /**
     * On progress update.
     *
     * @param download the download
     */
    public void onProgress(Download download);
}

private Download mCurrent;

/**
 * Sets the on progress listener.
 *
 * @param listener the new on progress listener
 */
public void setOnProgressListener(OnProgressListener listener)
{
    mOnProgressListener = listener;
}

/**
 * Gets the active download.
 *
 * @return the active download
 */
public Download getActiveDownload()
{
    return mCurrent;
}

/* (non-Javadoc)
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected Void doInBackground(Download... params) {
    int count = params.length;
    for (int i = 0; i < count; i++) {
        mCurrent = params[i];
        if(mCurrent == null)
        {
            continue;
        }
        mCurrent.setDownloadProgressListener(new Download.OnDownloadProgressListener() {

            @Override
            public void onDownloadProgress(Download download, int bytesDownloaded,
                    int bytesTotal) {
                publishProgress(download);
            }
        });
        mCurrent.setOnStatusChangedListener(new Download.OnStatusChangedListener() {

            @Override
            public void onStatusChanged(Download download, int status) {
                publishProgress(download);
            }
        });
        mCurrent.download();
        //publishProgress(mCurrent); redundant call
        if(this.isCancelled())
            break;
    }
    return null;
}

/* (non-Javadoc)
 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
 */
public void onPostExecute(Void v)
{
    //TODO notify completion.
}

/* (non-Javadoc)
 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
 */
@Override
protected void onProgressUpdate(Download... progress) {
    if(mOnProgressListener != null)
    {
        for(Download d:progress)
        {
            mOnProgressListener.onProgress(d);
        }
    }
}

}

I have a Downloader Service that loads a list of downloads to run from my database. 我有一个Downloader Service,它可以下载要从我的数据库运行的下载列表。 It then creates an ASyncTask that will run the downloads in a background Thread. 然后,它创建一个ASyncTask,它将在后台线程中运行下载。

Why not just use an IntentService , considering that it already has a background thread for you? 考虑到IntentService已经为您提供了一个后台线程,为什么不使用它呢? Here is a sample project demonstrating using an IntentService for downloads. 这是一个示例项目,演示使用IntentService进行下载。

I don't currently have a way to tell the service that the Downloader has completed. 我目前无法告诉服务下载程序已完成。

Call stopSelf() from onPostExecute() . onPostExecute()调用stopSelf() onPostExecute() Better yet, use IntentService , which will automatically shut down when there is no more work to be done. 更好的是,使用IntentService ,它将在没有更多工作要做时自动关闭。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM