因为解一个bug,所以大体的看了下Android4.3 的DownloadProvider模块,现在通过在写博客的过程中进一步的熟悉它,首先其源码位置于package/provider/DownloadProvider;
界面部分代码在packages/providers/DownloadProvider/ui/src下;
逻辑部分代码位于packages/providers/DownloadProvider/src下;
首先介绍几个关键的类,来有个大体的认识:
1、DownloadProvider:看名字就知道它是数据库操作的封装,继承自ContentProvider;
2、DownloadManager:大部分逻辑是进一步封装数据操作,供外部调用;
3、DownloadService:封装文件download,delete等操作,并且操纵下载的norification;继承自Service;
4、DownloadNotifier:状态栏Notification逻辑;
5、DownloadReceiver:配合DownloadNotifier进行文件的操作及其Notification;
6、DownloadList:Download app主界面,文件界面交互;
接下来还需要看一下Download的DataBase结构;它包括两张表:downloads和request_headers,来看看创建代码:
private void createDownloadsTable(SQLiteDatabase db) {
try {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
db.execSQL("CREATE TABLE " + DB_TABLE + "(" +
Downloads.Impl._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.COLUMN_URI + " TEXT, " +
Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " +
Downloads.Impl.COLUMN_APP_DATA + " TEXT, " +
Downloads.Impl.COLUMN_NO_INTEGRITY + " BOOLEAN, " +
Downloads.Impl.COLUMN_FILE_NAME_HINT + " TEXT, " +
Constants.OTA_UPDATE + " BOOLEAN, " +
Downloads.Impl._DATA + " TEXT, " +
Downloads.Impl.COLUMN_MIME_TYPE + " TEXT, " +
Downloads.Impl.COLUMN_DESTINATION + " INTEGER, " +
Constants.NO_SYSTEM_FILES + " BOOLEAN, " +
Downloads.Impl.COLUMN_VISIBILITY + " INTEGER, " +
Downloads.Impl.COLUMN_CONTROL + " INTEGER, " +
Downloads.Impl.COLUMN_STATUS + " INTEGER, " +
Downloads.Impl.COLUMN_FAILED_CONNECTIONS + " INTEGER, " +
Downloads.Impl.COLUMN_LAST_MODIFICATION + " BIGINT, " +
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_CLASS + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " +
Downloads.Impl.COLUMN_COOKIE_DATA + " TEXT, " +
Downloads.Impl.COLUMN_USER_AGENT + " TEXT, " +
Downloads.Impl.COLUMN_REFERER + " TEXT, " +
Downloads.Impl.COLUMN_TOTAL_BYTES + " INTEGER, " +
Downloads.Impl.COLUMN_CURRENT_BYTES + " INTEGER, " +
Constants.ETAG + " TEXT, " +
Constants.UID + " INTEGER, " +
Downloads.Impl.COLUMN_OTHER_UID + " INTEGER, " +
Downloads.Impl.COLUMN_TITLE + " TEXT, " +
Downloads.Impl.COLUMN_DESCRIPTION + " TEXT, " +
Constants.MEDIA_SCANNED + " BOOLEAN);");
} catch (SQLException ex) {
Log.e(Constants.TAG, "couldn't create table in downloads database");
throw ex;
}
}
private void createHeadersTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE);
db.execSQL("CREATE TABLE " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE + "(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" +
");");
}
解析需要按照一个主要的流程来讲解,我就以Browser中下载文件来作为讲解的入口吧;
首先,当我在网页中点击下载文件按钮后,开始下载文件,这里Browser中调用的代码是:
private void createDownloadsTable(SQLiteDatabase db) {
try {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
db.execSQL("CREATE TABLE " + DB_TABLE + "(" +
Downloads.Impl._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.COLUMN_URI + " TEXT, " +
Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " +
Downloads.Impl.COLUMN_APP_DATA + " TEXT, " +
Downloads.Impl.COLUMN_NO_INTEGRITY + " BOOLEAN, " +
Downloads.Impl.COLUMN_FILE_NAME_HINT + " TEXT, " +
Constants.OTA_UPDATE + " BOOLEAN, " +
Downloads.Impl._DATA + " TEXT, " +
Downloads.Impl.COLUMN_MIME_TYPE + " TEXT, " +
Downloads.Impl.COLUMN_DESTINATION + " INTEGER, " +
Constants.NO_SYSTEM_FILES + " BOOLEAN, " +
Downloads.Impl.COLUMN_VISIBILITY + " INTEGER, " +
Downloads.Impl.COLUMN_CONTROL + " INTEGER, " +
Downloads.Impl.COLUMN_STATUS + " INTEGER, " +
Downloads.Impl.COLUMN_FAILED_CONNECTIONS + " INTEGER, " +
Downloads.Impl.COLUMN_LAST_MODIFICATION + " BIGINT, " +
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_CLASS + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " +
Downloads.Impl.COLUMN_COOKIE_DATA + " TEXT, " +
Downloads.Impl.COLUMN_USER_AGENT + " TEXT, " +
Downloads.Impl.COLUMN_REFERER + " TEXT, " +
Downloads.Impl.COLUMN_TOTAL_BYTES + " INTEGER, " +
Downloads.Impl.COLUMN_CURRENT_BYTES + " INTEGER, " +
Constants.ETAG + " TEXT, " +
Constants.UID + " INTEGER, " +
Downloads.Impl.COLUMN_OTHER_UID + " INTEGER, " +
Downloads.Impl.COLUMN_TITLE + " TEXT, " +
Downloads.Impl.COLUMN_DESCRIPTION + " TEXT, " +
Constants.MEDIA_SCANNED + " BOOLEAN);");
} catch (SQLException ex) {
Log.e(Constants.TAG, "couldn't create table in downloads database");
throw ex;
}
}
private void createHeadersTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE);
db.execSQL("CREATE TABLE " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE + "(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" +
");");
}
获得DownloadManager的实例,组建一个DownloadManager.Request参数,在线程中调用其enqueue函数进行下载请求;看看这个qnqueue函数做了什么:
public long enqueue(Request request) {
ContentValues values = request.toContentValues(mPackageName);
Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
long id = Long.parseLong(downloadUri.getLastPathSegment());
return id;
}
enqueue函数主要是将Rquest实例分解组成一个ContentValues实例,并且添加到数据库中,函数返回插入的这条数据返回的ID;
ContentResolver.insert函数会调用到DownloadProvider实现的ContentProvider的insert函数中去;
......
//将相关的请求参数,配置等插入到downloads数据库;
long rowID = db.insert(DB_TABLE, null, filteredValues);
......
//将相关的请求参数,配置等插入到request_headers数据库中;
insertRequestHeaders(db, rowID, values);
......
if (values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION) ==
Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
// When notification is requested, kick off service to process all
// relevant downloads.
//启动DownloadService进行下载及其它工作
if (Downloads.Impl.isNotificationToBeDisplayed(vis)) {
context.startService(new Intent(context, DownloadService.class));
}
} else {
context.startService(new Intent(context, DownloadService.class));
}
notifyContentChanged(uri, match);
return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, rowID);
接下来就是DownloadService,应该是大头了,主要的下载任务就是通过它来完成的;startService启动DownloadService,首先当然是OnCreate函数了:
@Override
public void onCreate() {
super.onCreate();
......
//mUpdateThread 以及mUpdateHandler
mUpdateThread = new HandlerThread(TAG + "-UpdateThread");
mUpdateThread.start();
mUpdateHandler = new Handler(mUpdateThread.getLooper(), mUpdateCallback);
mScanner = new DownloadScanner(this);
//DownloadNotifier对象
mNotifier = new DownloadNotifier(this);
mNotifier.cancelAll();
mObserver = new DownloadManagerContentObserver();
//注册监听Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI的Observer
getContentResolver().registerContentObserver(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
true, mObserver);
}
创建的一个HandlerThread对象mUpdateThread并且start;用Handler、Message来进行后续的逻辑处理;
再来看看OnStartCommand函数:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int returnValue = super.onStartCommand(intent, flags, startId);
mLastStartId = startId;
//enqueueUpdate
enqueueUpdate();
return returnValue;
}
enqueueUpdate方法中mUpdateHandler发送一个MSG_UPDATE Message,mUpdateCallback中接收到并且处理:
private Handler.Callback mUpdateCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
final int startId = msg.arg1;
final boolean isActive;
synchronized (mDownloads) {
isActive = updateLocked();
}
......
if (isActive) {
//如果Active,则会在Delayed 5×60000ms后发送MSG_FINAL_UPDATE Message,主要是为了“any finished operations that didn't trigger an update pass.”
enqueueFinalUpdate();
} else {
//如果没有Active的任务正在进行,就会停止Service以及其它
if (stopSelfResult(startId)) {
if (DEBUG_LIFECYCLE) Log.v(TAG, "Nothing left; stopped");
getContentResolver().unregisterContentObserver(mObserver);
mScanner.shutdown();
mUpdateThread.quit();
}
}
return true;
}
};
重点是updateLocked()函数,我们来看看;
private boolean updateLocked() {
final long now = mSystemFacade.currentTimeMillis();
boolean isActive = false;
long nextActionMillis = Long.MAX_VALUE;
//mDownloads初始化是一个空的Map<Long, DownloadInfo>
final Set<Long> staleIds = Sets.newHashSet(mDownloads.keySet());
final ContentResolver resolver = getContentResolver();
//获取所有的DOWNLOADS任务
final Cursor cursor = resolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
null, null, null, null);
try {
final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
final int idColumn = cursor.getColumnIndexOrThrow(Downloads.Impl._ID);
//迭代Download Cusor
while (cursor.moveToNext()) {
final long id = cursor.getLong(idColumn);
staleIds.remove(id);
DownloadInfo info = mDownloads.get(id);
//开始时,mDownloads是没有任何内容的,info==null
if (info != null) {
//从数据库更新最新的Download info信息,来监听数据库的改变并且反应到界面上
updateDownload(reader, info, now);
} else {
//添加新下载的Dwonload info到mDownloads,并且从数据库读取新的Dwonload info
info = insertDownloadLocked(reader, now);
}
//这里的mDeleted参数表示的是当我删除了正在或者已经下载的内容时,首先数据库会update这个info.mDeleted为true,而不是直接删除文件
if (info.mDeleted) {
//不详细解释delete函数,主要是删除数据库内容和现在文件内容
if (!TextUtils.isEmpty(info.mMediaProviderUri)) {
resolver.delete(Uri.parse(info.mMediaProviderUri), null, null);
}
deleteFileIfExists(info.mFileName);
resolver.delete(info.getAllDownloadsUri(), null, null);
} else {
// 开始下载文件
final boolean activeDownload = info.startDownloadIfReady(mExecutor);
// 开始media scanner
final boolean activeScan = info.startScanIfReady(mScanner);
isActive |= activeDownload;
isActive |= activeScan;
}
// Keep track of nearest next action
nextActionMillis = Math.min(info.nextActionMillis(now), nextActionMillis);
}
} finally {
cursor.close();
}
// Clean up stale downloads that disappeared
for (Long id : staleIds) {
deleteDownloadLocked(id);
}
// Update notifications visible to user
mNotifier.updateWith(mDownloads.values());
if (nextActionMillis > 0 && nextActionMillis < Long.MAX_VALUE) {
final Intent intent = new Intent(Constants.ACTION_RETRY);
intent.setClass(this, DownloadReceiver.class);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, now + nextActionMillis,
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT));
}
return isActive;
}
重点来看看文件的下载,startDownloadIfReady函数:
public boolean startDownloadIfReady(ExecutorService executor) {
synchronized (this) {
final boolean isReady = isReadyToDownload();
final boolean isActive = mSubmittedTask != null && !mSubmittedTask.isDone();
if (isReady && !isActive) {
//更新数据库的任务状态为STATUS_RUNNING
if (mStatus != Impl.STATUS_RUNNING) {
mStatus = Impl.STATUS_RUNNING;
ContentValues values = new ContentValues();
values.put(Impl.COLUMN_STATUS, mStatus);
mContext.getContentResolver().update(getAllDownloadsUri(), values, null, null);
}
//开始下载任务
mTask = new DownloadThread(
mContext, mSystemFacade, this, mStorageManager, mNotifier);
mSubmittedTask = executor.submit(mTask);
}
return isReady;
}
}
跟踪DownloadThread,因为代码太多,贴出现在的主体部分来着重看看:
private void executeDownload(State state) throws StopRequestException {
while (state.mRedirectionCount++ < Constants.MAX_REDIRECTS) {
// Open connection and follow any redirects until we have a useful
// response with body.
HttpURLConnection conn = null;
try {
checkConnectivity();
conn = (HttpURLConnection) state.mUrl.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setConnectTimeout(DEFAULT_TIMEOUT);
conn.setReadTimeout(DEFAULT_TIMEOUT);
addRequestHeaders(state, conn);
final int responseCode = conn.getResponseCode();
switch (responseCode) {
case HTTP_OK: ......
processResponseHeaders(state, conn);
transferData(state, conn);
return;
case HTTP_PARTIAL:
......
return;
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
case HTTP_TEMP_REDIRECT:
......
continue;
case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
......
case HTTP_UNAVAILABLE:
......
case HTTP_INTERNAL_ERROR:
......
default:
......
}
} catch (IOException e) {
......
} finally {
if (conn != null) conn.disconnect();
}
}
跟踪transferData函数:
private void transferData(State state, HttpURLConnection conn) throws StopRequestException {
......
in = conn.getInputStream();
......
//获取InputStream和OutPutStream
if (DownloadDrmHelper.isDrmConvertNeeded(state.mMimeType)) {
drmClient = new DrmManagerClient(mContext);
final RandomAccessFile file = new RandomAccessFile(
new File(state.mFilename), "rw");
out = new DrmOutputStream(drmClient, file, state.mMimeType);
outFd = file.getFD();
} else {
out = new FileOutputStream(state.mFilename, true);
outFd = ((FileOutputStream) out).getFD();
}
......
// Start streaming data, periodically watch for pause/cancel
// commands and checking disk space as needed.
transferData(state, in, out);
......
}
进一步调用到transferData(state, in, out)函数中去,对获得到的InputStream和OutPutStream进行处理;
private void transferData(State state, InputStream in, OutputStream out)
throws StopRequestException {
final byte data[] = new byte[Constants.BUFFER_SIZE];
for (;;) {
//从InputStream中读取内容信息,“in.read(data)”,并且对数据库中文件下载大小进行更新
int bytesRead = readFromResponse(state, data, in);
if (bytesRead == -1) { // success, end of stream already reached
handleEndOfStream(state);
return;
}
state.mGotData = true;
//利用OutPutStream写入读取的InputStream,"out.write(data, 0, bytesRead)"
writeDataToDestination(state, data, bytesRead, out);
state.mCurrentBytes += bytesRead;
reportProgress(state);
}
checkPausedOrCanceled(state);
}
}
至此,下载文件的流程就说完了,继续回到DownloadService的updateLocked()函数中来;重点来分析DownloadNotifier的updateWith()函数,这个方法用来更新Notification,方法的代码很多,我就不详细的逐行讲解;
//这段代码是根据不同的状态设置不同的Notification的icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
//这段代码是根据不同的状态来设置不同的notification Intent
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
// build a synthetic uri for intent identification purposes
final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
final Intent intent = new Intent(Constants.ACTION_LIST,
uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
builder.setAutoCancel(true);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
//这段代码是更新下载的Progress
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
最后一段太多就不贴出来了,主要用来根据不同的状态来设置不同的Notification的title和description;并且最后发出通知;
mNotifManager.notify(tag, 0, notif);
至此,利用下载的过程来讲解一下系统的DownloadProvider就完了;
文章讲的不是特别的细,大体有个认识罢了,可以对DownloadProvider有个更深的认识;
最后,我修改的bug是,当下载一个文件完成以后,进入download app删除下载的文件,然后下拉通知栏,点击那一条目,”unfortnately, the process android.process.media has stopped.“,logcat如下:
12-25 05:49:48.226: E/AndroidRuntime(1238): FATAL EXCEPTION: DownloadReceiver
12-25 05:49:48.226: E/AndroidRuntime(1238): java.lang.IllegalArgumentException: Missing download 1
12-25 05:49:48.226: E/AndroidRuntime(1238): at com.android.providers.downloads.OpenHelper.buildViewIntent(OpenHelper.java:48)
12-25 05:49:48.226: E/AndroidRuntime(1238): at com.android.providers.downloads.DownloadReceiver.openDownload(DownloadReceiver.java:165)
12-25 05:49:48.226: E/AndroidRuntime(1238): at com.android.providers.downloads.DownloadReceiver.handleNotificationBroadcast(DownloadReceiver.java:119)
12-25 05:49:48.226: E/AndroidRuntime(1238): at com.android.providers.downloads.DownloadReceiver.access$000(DownloadReceiver.java:45)
12-25 05:49:48.226: E/AndroidRuntime(1238): at com.android.providers.downloads.DownloadReceiver$1.run(DownloadReceiver.java:99)
12-25 05:49:48.226: E/AndroidRuntime(1238): at android.os.Handler.handleCallback(Handler.java:730)
12-25 05:49:48.226: E/AndroidRuntime(1238): at android.os.Handler.dispatchMessage(Handler.java:92)
12-25 05:49:48.226: E/AndroidRuntime(1238): at android.os.Looper.loop(Looper.java:137)
12-25 05:49:48.226: E/AndroidRuntime(1238): at android.os.HandlerThread.run(HandlerThread.java:61)
打开文件,原因无法找到对应的download 条目;我修改方法是在删除下载条目时,同时删除notification,其实android原生是有的,但是其有问题,逻辑不严谨;
修改DownloadNotifier类中updateWithLocked方法;加了一个info.mDeleted的判断,来使当文件被删除时,清除对应的Notification;
else if (type == TYPE_COMPLETE) {
if(!info.mDeleted){
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
} else {
return;
}
}