FileDocCategorySizeDatePackage
DownloadManagerBaseTest.javaAPI DocAndroid 5.1 API21534Thu Mar 12 22:22:12 GMT 2015com.android.frameworks.downloadmanagertests

DownloadManagerBaseTest

public class DownloadManagerBaseTest extends android.test.InstrumentationTestCase
Base class for Instrumented tests for the Download Manager.

Fields Summary
protected android.app.DownloadManager
mDownloadManager
protected String
mFileType
protected android.content.Context
mContext
protected static final int
DEFAULT_FILE_SIZE
protected static final int
FILE_BLOCK_READ_SIZE
protected static final String
LOG_TAG
protected static final int
HTTP_OK
protected static final int
HTTP_REDIRECT
protected static final int
HTTP_PARTIAL_CONTENT
protected static final int
HTTP_NOT_FOUND
protected static final int
HTTP_SERVICE_UNAVAILABLE
protected static final int
DEFAULT_MAX_WAIT_TIME
protected static final int
DEFAULT_WAIT_POLL_TIME
protected static final int
WAIT_FOR_DOWNLOAD_POLL_TIME
protected static final int
MAX_WAIT_FOR_DOWNLOAD_TIME
protected static final int
MAX_WAIT_FOR_LARGE_DOWNLOAD_TIME
private DownloadFinishedListener
mListener
private Thread
mListenerThread
Constructors Summary
Methods Summary
private longgetBytesDownloaded(long id)

        DownloadManager.Query q = new DownloadManager.Query();
        q.setFilterById(id);
        Cursor response = mDownloadManager.query(q);
        if (response.getCount() < 1) {
            Log.i(LOG_TAG, String.format("Query to download manager returned nothing for id %d",id));
            response.close();
            return -1;
        }
        while(response.moveToNext()) {
            int index = response.getColumnIndex(DownloadManager.COLUMN_ID);
            if (id == response.getLong(index)) {
                break;
            }
        }
        int index = response.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
        if (index < 0) {
            Log.i(LOG_TAG, String.format("No downloaded bytes for id %d", id));
            response.close();
            return -1;
        }
        long size = response.getLong(index);
        response.close();
        return size;
    
protected android.database.CursorgetCursor(long id)
Performs a query based on ID and returns a Cursor for the query.

param
id The id of the download in DL Manager; pass -1 to query all downloads
return
A cursor for the query results

        Query query = new Query();
        if (id != -1) {
            query.setFilterById(id);
        }

        Cursor cursor = mDownloadManager.query(query);
        int currentWaitTime = 0;

        try {
            while (!cursor.moveToFirst()) {
                Thread.sleep(DEFAULT_WAIT_POLL_TIME);
                currentWaitTime += DEFAULT_WAIT_POLL_TIME;
                if (currentWaitTime > DEFAULT_MAX_WAIT_TIME) {
                    fail("timed out waiting for a non-null query result");
                }
                cursor.requery();
            }
        } catch (Exception e) {
            cursor.close();
            throw e;
        }
        return cursor;
    
private booleanhasDownloadFinished(long id)
Checks with the download manager if the give download is finished.

param
id id of the download to check
return
true if download is finished, false otherwise.

        Query q = new Query();
        q.setFilterById(id);
        q.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
        Cursor cursor = mDownloadManager.query(q);
        boolean finished = cursor.getCount() == 1;
        cursor.close();
        return finished;
    
protected com.android.frameworks.downloadmanagertests.DownloadManagerBaseTest$DownloadFinishedListenerregisterDownloadsListener()
Helper to create and register a new MultipleDownloadCompletedReciever This is used to track many simultaneous downloads by keeping count of all the downloads that have completed.

return
A new receiver that records and can be queried on how many downloads have completed.
throws
InterruptedException

        DownloadFinishedListener listener = new DownloadFinishedListener();
        mListenerThread = new Thread(listener);
        mListenerThread.start();
        mContext.registerReceiver(listener, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE), null, listener.getHandler());
        return listener;
    
protected voidremoveAllCurrentDownloads()
Helper to remove all downloads that are registered with the DL Manager. Note: This gives us a clean slate b/c it includes downloads that are pending, running, paused, or have completed.

        Log.i(LOG_TAG, "Removing all current registered downloads...");
        Cursor cursor = mDownloadManager.query(new Query());
        try {
            if (cursor.moveToFirst()) {
                do {
                    int index = cursor.getColumnIndex(DownloadManager.COLUMN_ID);
                    long downloadId = cursor.getLong(index);

                    mDownloadManager.remove(downloadId);
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
        }
    
protected voidsetAirplaneModeOn(boolean enable)
Helper to enables or disables airplane mode. If successful, it also broadcasts an intent indicating that the mode has changed. Note: Needs the following permission: android.permission.WRITE_SETTINGS

param
enable true if airplane mode should be ON, false if it should be OFF

        int state = enable ? 1 : 0;

        // Change the system setting
        Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON,
                state);

        String timeoutMessage = "Timed out waiting for airplane mode to be " +
                (enable ? "enabled!" : "disabled!");

        // wait for airplane mode to change state
        int currentWaitTime = 0;
        while (Settings.System.getInt(mContext.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON, -1) != state) {
            timeoutWait(currentWaitTime, DEFAULT_WAIT_POLL_TIME, DEFAULT_MAX_WAIT_TIME,
                    timeoutMessage);
        }

        // Post the intent
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", true);
        mContext.sendBroadcast(intent);
    
public voidsetUp()
{@inheritDoc}

        super.setUp();
        mContext = getInstrumentation().getContext();
        mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        mListener = registerDownloadsListener();
    
protected voidsetWiFiStateOn(boolean enable)
Enables or disables WiFi. Note: Needs the following permissions: android.permission.ACCESS_WIFI_STATE android.permission.CHANGE_WIFI_STATE

param
enable true if it should be enabled, false if it should be disabled

        Log.i(LOG_TAG, "Setting WiFi State to: " + enable);
        WifiManager manager = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);

        manager.setWifiEnabled(enable);

        String timeoutMessage = "Timed out waiting for Wifi to be "
            + (enable ? "enabled!" : "disabled!");

        WiFiChangedReceiver receiver = new WiFiChangedReceiver(mContext);
        mContext.registerReceiver(receiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));

        synchronized (receiver) {
            long timeoutTime = SystemClock.elapsedRealtime() + DEFAULT_MAX_WAIT_TIME;
            boolean timedOut = false;

            while (receiver.getWiFiIsOn() != enable && !timedOut) {
                try {
                    receiver.wait(DEFAULT_WAIT_POLL_TIME);

                    if (SystemClock.elapsedRealtime() > timeoutTime) {
                        timedOut = true;
                    }
                }
                catch (InterruptedException e) {
                    // ignore InterruptedExceptions
                }
            }
            if (timedOut) {
                fail(timeoutMessage);
            }
        }
        assertEquals(enable, receiver.getWiFiIsOn());
    
public voidtearDown()

        mContext.unregisterReceiver(mListener);
        mListener.cancel();
        mListenerThread.join();
        super.tearDown();
    
private inttimeoutWait(int currentTotalWaitTime, long poll, long maxTimeoutMillis, java.lang.String timedOutMessage)
Helper function to synchronously wait, or timeout if the maximum threshold has been exceeded.

param
currentTotalWaitTime The total time waited so far
param
poll The amount of time to wait
param
maxTimeoutMillis The total wait time threshold; if we've waited more than this long, we timeout and fail
param
timedOutMessage The message to display in the failure message if we timeout
return
The new total amount of time we've waited so far
throws
TimeoutException if timed out waiting for SD card to mount

        long now = SystemClock.elapsedRealtime();
        long end = now + poll;

        // if we get InterruptedException's, ignore them and just keep sleeping
        while (now < end) {
            try {
                Thread.sleep(end - now);
            } catch (InterruptedException e) {
                // ignore interrupted exceptions
            }
            now = SystemClock.elapsedRealtime();
        }

        currentTotalWaitTime += poll;
        if (currentTotalWaitTime > maxTimeoutMillis) {
            throw new TimeoutException(timedOutMessage);
        }
        return currentTotalWaitTime;
    
protected voidverifyFileSize(android.os.ParcelFileDescriptor pfd, long size)
Helper to verify the size of a file.

param
pfd The input file to compare the size of
param
size The expected size of the file

        assertEquals(pfd.getStatSize(), size);
    
protected booleanwaitForDownload(long id, long timeoutMillis)
Helper to wait for a particular download to finish, or else a timeout to occur.

param
id The download id to query on (wait for)
param
poll The amount of time to wait
param
timeoutMillis The max time (in ms) to wait for the download(s) to complete

        return mListener.waitForDownloadToFinish(id, timeoutMillis);
    
protected voidwaitForDownloadToStart(long dlRequest)
Synchronously waits for a download to start.

param
dlRequest the download request id used by Download Manager to track the download.
throws
Exception if timed out while waiting for SD card to mount

        Cursor cursor = getCursor(dlRequest);
        try {
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int value = cursor.getInt(columnIndex);
            int currentWaitTime = 0;

            while (value != DownloadManager.STATUS_RUNNING &&
                    (value != DownloadManager.STATUS_FAILED) &&
                    (value != DownloadManager.STATUS_SUCCESSFUL)) {
                Log.i(LOG_TAG, "Waiting for download to start...");
                currentWaitTime = timeoutWait(currentWaitTime, WAIT_FOR_DOWNLOAD_POLL_TIME,
                        MAX_WAIT_FOR_DOWNLOAD_TIME, "Timed out waiting for download to start!");
                cursor.requery();
                assertTrue(cursor.moveToFirst());
                columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                value = cursor.getInt(columnIndex);
            }
            assertFalse("Download failed immediately after start",
                    value == DownloadManager.STATUS_FAILED);
        } finally {
            cursor.close();
        }
    
protected voidwaitForExternalStoreMount()
Synchronously waits for external store to be mounted (eg: SD Card).

throws
InterruptedException if interrupted
throws
Exception if timed out waiting for SD card to mount

        String extStorageState = Environment.getExternalStorageState();
        int currentWaitTime = 0;
        while (!extStorageState.equals(Environment.MEDIA_MOUNTED)) {
            Log.i(LOG_TAG, "Waiting for SD card...");
            currentWaitTime = timeoutWait(currentWaitTime, DEFAULT_WAIT_POLL_TIME,
                    DEFAULT_MAX_WAIT_TIME, "Timed out waiting for SD Card to be ready!");
            extStorageState = Environment.getExternalStorageState();
        }
    
protected booleanwaitForMultipleDownloads(java.util.Set ids, long timeout)

        return mListener.waitForMultipleDownloadsToFinish(ids, timeout);
    
protected voidwaitToReceiveData(long id, long bytesToReceive)
Synchronously waits for the download manager to start incrementing the number of bytes downloaded so far.

param
id DownloadManager download id that needs to be checked.
param
bytesToReceive how many bytes do we need to wait to receive.
throws
Exception if timed out while waiting for the file to grow in size.

        int currentWaitTime = 0;
        long expectedSize = getBytesDownloaded(id) + bytesToReceive;
        long currentSize = 0;
        while ((currentSize = getBytesDownloaded(id)) <= expectedSize) {
            Log.i(LOG_TAG, String.format("expect: %d, cur: %d. Waiting for file to be written to...",
                    expectedSize, currentSize));
            currentWaitTime = timeoutWait(currentWaitTime, WAIT_FOR_DOWNLOAD_POLL_TIME,
                    MAX_WAIT_FOR_DOWNLOAD_TIME, "Timed out waiting for file to be written to.");
        }