如何在ASyncTask旋转完成后结束android服务?

时间:2011-02-18 15:30:52

标签: java android service android-intent android-asynctask

我有一个Downloader服务,可以加载从我的数据库运行的下载列表。

然后创建一个ASyncTask,它将在后台线程中运行下载。

这一切都运行得很好,但问题是我目前没有办法告诉服务该下载器已经完成。我不得不从ASyncTask的onPostExecute函数(在UIThread上运行)向服务发送消息。

我不能简单地远程关闭服务,因为当ASyncTask完成时,服务还有一些工作要做。

我考虑过从服务中注册一个监听器并在onPostExecute中调用它,但我认为这会导致在Task完成之前关闭服务或一些threadlocking问题等问题。

如何从ASyncTask向我的Downloader服务发送消息(如广播意图)?

修改
这里有一些代码让你对我正在做的事感到困惑。

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

}

1 个答案:

答案 0 :(得分:6)

  

我有一个Downloader Service,可以加载从我的数据库运行的下载列表。   然后它创建一个ASyncTask,它将在后台线程中运行下载。

为什么不使用IntentService,考虑到它已经有了后台线程? Here is a sample project使用IntentService进行下载演示。

  

我目前无法告诉服务该下载器已完成。

stopSelf()致电onPostExecute()。更好的是,使用IntentService,当没有更多的工作要做时,它会自动关闭。