├── .classpath
├── .gitattributes
├── .gitignore
├── .project
├── .settings
├── org.eclipse.core.resources.prefs
└── org.eclipse.jdt.core.prefs
├── AndroidManifest.xml
├── README.md
├── assets
└── icudt46l.zip
├── ic_launcher-web.png
├── libs
├── armeabi-v7a
│ ├── libdatabase_sqlcipher.so
│ ├── libsqlcipher_android.so
│ └── libstlport_shared.so
├── armeabi
│ ├── libdatabase_sqlcipher.so
│ ├── libsqlcipher_android.so
│ └── libstlport_shared.so
├── commons-codec.jar
├── guava-r09.jar
├── sqlcipher.jar
└── x86
│ ├── libdatabase_sqlcipher.so
│ ├── libsqlcipher_android.so
│ └── libstlport_shared.so
├── proguard-project.txt
├── project.properties
├── res
├── drawable-hdpi
│ └── ic_launcher.png
├── drawable-mdpi
│ └── ic_launcher.png
├── drawable-xhdpi
│ └── ic_launcher.png
├── drawable-xxhdpi
│ └── ic_launcher.png
├── layout
│ ├── activity_download.xml
│ └── activity_main.xml
├── values-v11
│ └── styles.xml
├── values-v14
│ └── styles.xml
└── values
│ ├── strings.xml
│ └── styles.xml
└── src
└── com
└── kindy
└── httpurlconnection
├── DownloadActivity.java
├── MainActivity.java
├── models
├── FileInfo.java
└── ThreadInfo.java
├── services
├── DownloadService.java
└── DownloadTask.java
└── utils
├── DBBaseHelper.java
├── DBDownloadHelper.java
├── Debug.java
├── HttpUtils.java
└── SQLiteUtils.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Windows image file caches
2 | Thumbs.db
3 | ehthumbs.db
4 |
5 | # Folder config file
6 | Desktop.ini
7 |
8 | # Recycle Bin used on file shares
9 | $RECYCLE.BIN/
10 |
11 | # Windows Installer files
12 | *.cab
13 | *.msi
14 | *.msm
15 | *.msp
16 |
17 | # Windows shortcuts
18 | *.lnk
19 |
20 | # =========================
21 | # Operating System Files
22 | # =========================
23 |
24 | # OSX
25 | # =========================
26 |
27 | .DS_Store
28 | .AppleDouble
29 | .LSOverride
30 |
31 | # Thumbnails
32 | ._*
33 |
34 | # Files that might appear on external disk
35 | .Spotlight-V100
36 | .Trashes
37 |
38 | # Directories potentially created on remote AFP share
39 | .AppleDB
40 | .AppleDesktop
41 | Network Trash Folder
42 | Temporary Items
43 | .apdisk
44 | bin
45 | gen
46 |
47 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | HttpURLConnection
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 |
30 | com.android.ide.eclipse.adt.AndroidNature
31 | org.eclipse.jdt.core.javanature
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding/=UTF-8
3 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
3 | org.eclipse.jdt.core.compiler.compliance=1.6
4 | org.eclipse.jdt.core.compiler.source=1.6
5 |
--------------------------------------------------------------------------------
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
10 |
11 |
12 |
13 |
14 |
19 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
32 |
33 |
34 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HttpURLConnection
2 | **主要功能:**
3 |
android HttpURLConnection 支持 http 和 https,
4 |
文件的断点继续下载功能。
5 |
数据库的加密
6 |
--------------------------------------------------------------------------------
/assets/icudt46l.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/assets/icudt46l.zip
--------------------------------------------------------------------------------
/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/ic_launcher-web.png
--------------------------------------------------------------------------------
/libs/armeabi-v7a/libdatabase_sqlcipher.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi-v7a/libdatabase_sqlcipher.so
--------------------------------------------------------------------------------
/libs/armeabi-v7a/libsqlcipher_android.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi-v7a/libsqlcipher_android.so
--------------------------------------------------------------------------------
/libs/armeabi-v7a/libstlport_shared.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi-v7a/libstlport_shared.so
--------------------------------------------------------------------------------
/libs/armeabi/libdatabase_sqlcipher.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi/libdatabase_sqlcipher.so
--------------------------------------------------------------------------------
/libs/armeabi/libsqlcipher_android.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi/libsqlcipher_android.so
--------------------------------------------------------------------------------
/libs/armeabi/libstlport_shared.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/armeabi/libstlport_shared.so
--------------------------------------------------------------------------------
/libs/commons-codec.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/commons-codec.jar
--------------------------------------------------------------------------------
/libs/guava-r09.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/guava-r09.jar
--------------------------------------------------------------------------------
/libs/sqlcipher.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/sqlcipher.jar
--------------------------------------------------------------------------------
/libs/x86/libdatabase_sqlcipher.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/x86/libdatabase_sqlcipher.so
--------------------------------------------------------------------------------
/libs/x86/libsqlcipher_android.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/x86/libsqlcipher_android.so
--------------------------------------------------------------------------------
/libs/x86/libstlport_shared.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/libs/x86/libstlport_shared.so
--------------------------------------------------------------------------------
/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-23
15 |
--------------------------------------------------------------------------------
/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/enjoy008/HttpURLConnection/40906371bbefc21248d6185e50055735378c6b48/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/layout/activity_download.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
12 |
13 |
18 |
19 |
25 |
26 |
31 |
32 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
14 |
15 |
19 |
20 |
24 |
25 |
30 |
31 |
--------------------------------------------------------------------------------
/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/res/values-v14/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | HttpURLConnection
4 |
5 |
6 |
--------------------------------------------------------------------------------
/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/DownloadActivity.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection;
2 |
3 | import net.sqlcipher.Cursor;
4 | import net.sqlcipher.database.SQLiteDatabase;
5 | import android.app.Activity;
6 | import android.content.BroadcastReceiver;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.IntentFilter;
10 | import android.os.Bundle;
11 | import android.view.View;
12 | import android.view.View.OnClickListener;
13 | import android.widget.Button;
14 | import android.widget.ProgressBar;
15 | import android.widget.TextView;
16 |
17 | import com.kindy.httpurlconnection.models.FileInfo;
18 | import com.kindy.httpurlconnection.services.DownloadService;
19 | import com.kindy.httpurlconnection.utils.DBBaseHelper;
20 | import com.kindy.httpurlconnection.utils.DBDownloadHelper;
21 | import com.kindy.httpurlconnection.utils.SQLiteUtils;
22 |
23 | public class DownloadActivity extends Activity {
24 |
25 | //定义组件
26 | private TextView mTextView;
27 | private ProgressBar mProgressBar;
28 | private Button btnStart, btnStop;
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_download);
34 |
35 | //初始化组件
36 | mTextView = (TextView) findViewById(R.id.textView);
37 | mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
38 | mProgressBar.setMax(100);
39 | btnStart = (Button) findViewById(R.id.btnStart);
40 | btnStop = (Button) findViewById(R.id.btnStop);
41 |
42 | //添加事件监听
43 | btnStart.setOnClickListener(mOnClickListener);
44 | btnStop.setOnClickListener(mOnClickListener);
45 |
46 | //注册广播接收器
47 | IntentFilter filter = new IntentFilter();
48 | filter.addAction(DownloadService.ACTION_UPDATE);
49 | registerReceiver(mReceiver,filter);
50 | }
51 |
52 | private OnClickListener mOnClickListener = new OnClickListener() {
53 |
54 | @Override
55 | public void onClick(View v) {
56 | switch(v.getId()) {
57 | case R.id.btnStart: {
58 | String url = "http://www.imooc.com/mobile/mukewang.apk";
59 | FileInfo downloadFile = new FileInfo(1, url, 0, 0);
60 |
61 |
62 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
63 | Cursor cursor = SQLiteUtils.getInstance().rawQuery(db, "select * from " + DBDownloadHelper.TABLE_FILE + " where id = ?", new String[]{"1"});
64 | if(cursor != null) {
65 | if(cursor.moveToFirst()) {
66 | downloadFile = new FileInfo(cursor);
67 | }
68 | cursor.close();
69 | }
70 | db.close();
71 |
72 | //通过intent传递参数给Service
73 | Intent intent = new Intent(DownloadActivity.this, DownloadService.class);
74 | intent.setAction(DownloadService.ACTION_START);
75 | intent.putExtra(DownloadService.FILE_INFO, downloadFile);
76 | startService(intent);
77 |
78 | mTextView.setText(downloadFile.getFileName());
79 | }
80 | break;
81 | case R.id.btnStop: {
82 | FileInfo downloadFile = null;
83 |
84 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
85 | Cursor cursor = SQLiteUtils.getInstance().rawQuery(db, "select * from " + DBDownloadHelper.TABLE_FILE + " where id = ?", new String[]{"1"});
86 | if(cursor != null) {
87 | if(cursor.moveToFirst()) {
88 | downloadFile = new FileInfo(cursor);
89 | }
90 | cursor.close();
91 | }
92 | db.close();
93 |
94 | if(downloadFile != null) {
95 | //通过intent传递参数给Service
96 | Intent intent = new Intent(DownloadActivity.this, DownloadService.class);
97 | intent.setAction(DownloadService.ACTION_STOP);
98 | intent.putExtra(DownloadService.FILE_INFO, downloadFile);
99 | startService(intent);
100 | }
101 | }
102 | break;
103 | }
104 | }
105 | };
106 |
107 | //帮助我们更新UI的广播接收器
108 | private BroadcastReceiver mReceiver = new BroadcastReceiver() {
109 | @Override
110 | public void onReceive(Context context, Intent intent) {
111 | if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {
112 | int fileId = intent.getIntExtra(DownloadService.NOTICE_FILE_ID, 0);
113 | int progress = (int) intent.getLongExtra(DownloadService.NOTICE_PROGRESS, 0);
114 | // int finished = intent.getIntExtra(KindyDownloadTask.NOTICE_PROGRESS, 0);
115 | mProgressBar.setProgress(progress);
116 | }
117 | }
118 | };
119 |
120 | @Override
121 | protected void onDestroy() {
122 | unregisterReceiver(mReceiver);
123 | super.onDestroy();
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 |
6 | import android.app.Activity;
7 | import android.content.Intent;
8 | import android.graphics.Bitmap;
9 | import android.graphics.BitmapFactory;
10 | import android.os.Bundle;
11 | import android.view.View;
12 | import android.widget.ImageView;
13 |
14 | import com.kindy.httpurlconnection.utils.DBBaseHelper;
15 | import com.kindy.httpurlconnection.utils.HttpUtils;
16 |
17 | public class MainActivity extends Activity {
18 |
19 | private ImageView img;
20 | private Bitmap bmp;
21 |
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_main);
26 |
27 |
28 | img = (ImageView) findViewById(R.id.img);
29 |
30 | DBBaseHelper.init(this.getApplicationContext());
31 | }
32 |
33 | public void click(View view) {
34 | System.out.println(this.getClass().getName() + " ================= click");
35 |
36 | new Thread() {
37 | public void run() {
38 |
39 | String url = "https://www.baidu.com/img/bd_logo1.png";
40 | InputStream is = HttpUtils.getInstance().getInputStream(url);
41 | if(is != null) {
42 | bmp = BitmapFactory.decodeStream(is);
43 | try {
44 | is.close();
45 | } catch (IOException e) { }
46 | }
47 |
48 | runOnUiThread(new Runnable() {
49 | public void run() {
50 | if(bmp == null) {
51 | img.setImageResource(R.drawable.ic_launcher);
52 | } else {
53 | img.setImageBitmap(bmp);
54 | }
55 |
56 | bmp = null;
57 | }
58 | });
59 |
60 | }
61 | }.start();
62 | }
63 |
64 | public void download(View view) {
65 | startActivity(new Intent(this, DownloadActivity.class));
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/models/FileInfo.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.models;
2 |
3 | import java.io.File;
4 | import java.io.Serializable;
5 |
6 | import android.content.ContentValues;
7 | import android.database.Cursor;
8 |
9 | public class FileInfo implements Serializable {
10 |
11 | /**
12 | *
13 | */
14 | private static final long serialVersionUID = 1L;
15 |
16 | public int id;
17 | public String url;
18 | public long length;
19 | public long progress;
20 |
21 | public FileInfo() {
22 | this(0, "", 0, 0);
23 | }
24 |
25 | public FileInfo(int id, String url, long progress, long length) {
26 | this.id = id;
27 | this.url = url;
28 | this.progress = progress;
29 | this.length = length;
30 | }
31 |
32 | public FileInfo(Cursor cursor) {
33 | id = cursor.getInt(cursor.getColumnIndex("id"));
34 | url = cursor.getString(cursor.getColumnIndex("url"));
35 | length = cursor.getLong(cursor.getColumnIndex("length"));
36 | progress = cursor.getLong(cursor.getColumnIndex("progress"));
37 | }
38 |
39 | public ContentValues toContentValues() {
40 | ContentValues values = new ContentValues();
41 |
42 | values.put("id", id);
43 | values.put("url", url);
44 | values.put("length", length +"");
45 | values.put("progress", progress +"");
46 |
47 | return values;
48 | }
49 |
50 | public String getFileName() {
51 | return getFileName(false);
52 | }
53 |
54 | public String getFileName(boolean isTemp) {
55 | String name = "tmp";
56 |
57 | int start = url.lastIndexOf(File.separator);
58 | if(start != -1) {
59 | name = url.substring(start+1);
60 | }
61 | if(isTemp) {
62 | name += ".tmp";
63 | }
64 |
65 | return name;
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/models/ThreadInfo.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.models;
2 |
3 | import android.content.ContentValues;
4 | import android.database.Cursor;
5 |
6 | public class ThreadInfo {
7 | public int id;
8 | public int fileId;
9 | public long position;
10 | public long end;
11 |
12 | public ThreadInfo(int id, int fileId, long position, long end) {
13 | this.id = id;
14 | this.fileId = fileId;
15 | this.position = position;
16 | this.end = end;
17 | }
18 |
19 | public ThreadInfo(Cursor cursor) {
20 | id = cursor.getInt(cursor.getColumnIndex("id"));
21 | fileId = cursor.getInt(cursor.getColumnIndex("fileId"));
22 | position = cursor.getLong(cursor.getColumnIndex("position"));
23 | end = cursor.getLong(cursor.getColumnIndex("end"));
24 | }
25 |
26 | public ContentValues toContentValues() {
27 | ContentValues values = new ContentValues();
28 |
29 | values.put("id", id);
30 | values.put("fileId", fileId);
31 | values.put("position", position +"");
32 | values.put("end", end +"");
33 |
34 | return values;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/services/DownloadService.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.services;
2 |
3 | import java.io.File;
4 | import java.util.ArrayList;
5 | import java.util.Collections;
6 | import java.util.List;
7 |
8 | import net.sqlcipher.database.SQLiteDatabase;
9 | import android.app.Service;
10 | import android.content.Intent;
11 | import android.os.Environment;
12 | import android.os.IBinder;
13 | import android.widget.Toast;
14 |
15 | import com.kindy.httpurlconnection.models.FileInfo;
16 | import com.kindy.httpurlconnection.utils.DBBaseHelper;
17 | import com.kindy.httpurlconnection.utils.DBDownloadHelper;
18 | import com.kindy.httpurlconnection.utils.Debug;
19 | import com.kindy.httpurlconnection.utils.SQLiteUtils;
20 |
21 | public class DownloadService extends Service {
22 |
23 | //路径标识
24 | public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
25 |
26 | public static final String NOTICE_FILE_ID = "notice_file_id";
27 | public static final String NOTICE_PROGRESS = "notice_progress";
28 | public static final String NOTICE_DOWNLOAD_FINISH = "notice_download_finish";
29 |
30 | public static final String FILE_INFO = "file_info";
31 |
32 | //开始标识
33 | public static final String ACTION_START = "action_start";
34 | //结束标识
35 | public static final String ACTION_STOP = "action_stop";
36 | public static final String ACTION_UPDATE = "action_update";
37 |
38 | //handler传递标识
39 | public static final int MSG_INIT = 0;
40 |
41 | //定义下载任务
42 | private List mDownloadTaskList;
43 |
44 | private DownloadTask getDownloadTask(int fileId) {
45 | synchronized (mDownloadTaskList) {
46 | for(DownloadTask t : mDownloadTaskList) {
47 | if(t.fileInfo.id == fileId) {
48 | return t;
49 | }
50 | }
51 | return null;
52 | }
53 | }
54 | private boolean addDownloadTask(DownloadTask task) {
55 | synchronized (mDownloadTaskList) {
56 | if(!mDownloadTaskList.contains(task)) {
57 | return mDownloadTaskList.add(task);
58 | }
59 | return false;
60 | }
61 | }
62 | private boolean removeDownloadTask(DownloadTask task) {
63 | synchronized (mDownloadTaskList) {
64 | return mDownloadTaskList.remove(task);
65 | }
66 | }
67 | private boolean removeDownloadTask(int fileId) {
68 | DownloadTask task = getDownloadTask(fileId);
69 | if(task != null) {
70 | task.cancel();
71 | }
72 | return removeDownloadTask(task);
73 | }
74 |
75 | @Override
76 | public void onCreate() {
77 | super.onCreate();
78 | mDownloadTaskList = Collections.synchronizedList(new ArrayList());
79 | }
80 |
81 | @Override
82 | public int onStartCommand(Intent intent, int flags, int startId) {
83 |
84 | if(intent != null) {
85 | if (ACTION_START.equals(intent.getAction())) {
86 | FileInfo downloadFile = (FileInfo) intent.getSerializableExtra(FILE_INFO);
87 | start(downloadFile);
88 | } else if (ACTION_STOP.equals(intent.getAction())) {
89 | FileInfo downloadFile = (FileInfo) intent.getSerializableExtra(FILE_INFO);
90 | stop(downloadFile);
91 | } else if (ACTION_UPDATE.equals(intent.getAction())) {
92 | FileInfo downloadFile = (FileInfo) intent.getSerializableExtra(FILE_INFO);
93 | update(downloadFile);
94 | }
95 | }
96 |
97 | return super.onStartCommand(intent, flags, startId);
98 | }
99 |
100 | private void start(FileInfo downloadFile) {
101 | DownloadTask task = getDownloadTask(downloadFile.id);
102 | if(task == null) {
103 | task = new DownloadTask(getApplicationContext(), downloadFile);
104 | task.download();
105 |
106 | addDownloadTask(task);
107 | }
108 | }
109 |
110 | private void stop(FileInfo downloadFile) {
111 | removeDownloadTask(downloadFile.id);
112 | }
113 |
114 | private void update(FileInfo downloadFile) {
115 | stop(downloadFile);
116 |
117 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
118 | if(downloadFile.progress == downloadFile.length) {
119 | File tempFile = new File(DOWNLOAD_PATH + downloadFile.getFileName(true));
120 | boolean succeed = tempFile.renameTo(new File(DOWNLOAD_PATH + downloadFile.getFileName()));
121 | Debug.o(this, " succeed : " + succeed);
122 |
123 | SQLiteUtils.getInstance().delete(db, DBDownloadHelper.TABLE_FILE, "id = ?", new String[]{downloadFile.id +""});
124 | Toast.makeText(getApplication(), "下载完成", Toast.LENGTH_SHORT).show();
125 | } else {
126 | SQLiteUtils.getInstance().update(db, DBDownloadHelper.TABLE_FILE, downloadFile.toContentValues(), "id = ?", new String[]{downloadFile.id +""});
127 | }
128 | db.close();
129 |
130 | // 结束后再通知一次
131 | Intent intent2 = new Intent(DownloadService.ACTION_UPDATE);
132 | intent2.putExtra(NOTICE_FILE_ID, downloadFile.id);
133 | intent2.putExtra(NOTICE_PROGRESS, downloadFile.progress * 100 / downloadFile.length);
134 | sendBroadcast(intent2);
135 | }
136 |
137 | @Override
138 | public IBinder onBind(Intent intent) {
139 | // TODO: Return the communication channel to the service.
140 | throw new UnsupportedOperationException("Not yet implemented");
141 | }
142 |
143 | }
144 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/services/DownloadTask.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.services;
2 |
3 | import java.io.File;
4 | import java.io.InputStream;
5 | import java.io.RandomAccessFile;
6 | import java.net.HttpURLConnection;
7 | import java.util.ArrayList;
8 |
9 | import net.sqlcipher.Cursor;
10 | import net.sqlcipher.database.SQLiteDatabase;
11 | import android.content.Context;
12 | import android.content.Intent;
13 | import android.os.Handler;
14 | import android.os.Message;
15 |
16 | import com.kindy.httpurlconnection.models.FileInfo;
17 | import com.kindy.httpurlconnection.models.ThreadInfo;
18 | import com.kindy.httpurlconnection.utils.DBBaseHelper;
19 | import com.kindy.httpurlconnection.utils.DBDownloadHelper;
20 | import com.kindy.httpurlconnection.utils.Debug;
21 | import com.kindy.httpurlconnection.utils.HttpUtils;
22 | import com.kindy.httpurlconnection.utils.SQLiteUtils;
23 |
24 | public class DownloadTask extends Thread {
25 | /** 开启下载 */
26 | private static final int OPEN_DOWNLOAD = 1;
27 | /** 更新进度 */
28 | private static final int UPDATE_PROGRESS = 2;
29 | /** 更新数据库中的线程信息 */
30 | private static final int UPDATE_SUBTASK = 3;
31 |
32 | private Context context;
33 | public FileInfo fileInfo;
34 | private boolean isRunning;
35 |
36 | private static final int mThreadCount = 2;
37 | private int mCurrentThreadCount = 0;
38 |
39 | public DownloadTask(Context context, FileInfo fileInfo) {
40 | this.context = context;
41 | this.fileInfo = fileInfo;
42 | isRunning = false;
43 | }
44 |
45 | /**
46 | * 开始下载
47 | */
48 | public void download() {
49 | if(isRunning) {
50 | return;
51 | }
52 |
53 | start();
54 | }
55 |
56 | /**
57 | * 取消下载
58 | */
59 | public void cancel() {
60 | isRunning = false;
61 | }
62 |
63 | public boolean isRunning() {
64 | return isRunning;
65 | }
66 |
67 | @Override
68 | public void run() {
69 | isRunning = true;
70 |
71 | if(fileInfo.length > 0) {
72 | mHandler.sendEmptyMessage(OPEN_DOWNLOAD);
73 | return;
74 | }
75 |
76 | HttpURLConnection conn = null;
77 | RandomAccessFile raf = null;
78 | try {
79 | //连接网络文件
80 | conn = HttpUtils.getInstance().createConnection(fileInfo.url);
81 | conn.setRequestMethod("GET");
82 | conn.setUseCaches(false);
83 | // conn.setRequestProperty("Accept-Encoding", "identity");//不采用gzip压缩
84 |
85 | //获得文件长度
86 | int length = -1;
87 | int responseCode = conn.getResponseCode();
88 | if (responseCode == HttpURLConnection.HTTP_OK) {
89 | length = conn.getContentLength();
90 | }
91 |
92 | Debug.o(this, " responseCode : " + responseCode + " length = " + length);
93 |
94 | if(length > 0) {
95 |
96 | File fileDir = new File(DownloadService.DOWNLOAD_PATH);
97 | if (!fileDir.exists()) {
98 | fileDir.mkdir();
99 | }
100 |
101 | File tempFile = new File(fileDir, fileInfo.getFileName(true));
102 | raf = new RandomAccessFile(tempFile, "rwd");
103 | // 设置文件长度
104 | raf.setLength(length);
105 |
106 | fileInfo.length = length;
107 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
108 | SQLiteUtils.getInstance().insert(db, DBDownloadHelper.TABLE_FILE, fileInfo.toContentValues());
109 | db.close();
110 |
111 | mHandler.sendEmptyMessage(OPEN_DOWNLOAD);
112 | }
113 | } catch (Exception e) {
114 | e.printStackTrace();
115 | } finally {
116 | if(raf != null) {
117 | try {
118 | raf.close();
119 | } catch (Exception e) {}
120 | }
121 | if(conn != null) {
122 | conn.disconnect();
123 | }
124 |
125 | }
126 | }
127 |
128 | private long mTime = 0;
129 | private Handler mHandler = new Handler(new Handler.Callback() {
130 |
131 | @Override
132 | public boolean handleMessage(Message msg) {
133 | if(OPEN_DOWNLOAD == msg.what) {
134 | if(fileInfo.length > 0) {
135 | ArrayList threadInfoList = new ArrayList();
136 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
137 | Cursor cursor = SQLiteUtils.getInstance().rawQuery(db, "select * from " + DBDownloadHelper.TABLE_THREAD + " where fileId = ?", new String[]{fileInfo.id +""});
138 | if(cursor != null) {
139 | while(cursor.moveToNext()) {
140 | ThreadInfo threadInfo = new ThreadInfo(cursor);
141 | threadInfoList.add(threadInfo);
142 | }
143 | cursor.close();
144 | }
145 |
146 | if(threadInfoList.size() == 0) {
147 | long len = fileInfo.length / mThreadCount;
148 | for(int i=0; i 500) {
171 | mTime = System.currentTimeMillis();
172 |
173 | Intent intent = new Intent(DownloadService.ACTION_UPDATE);
174 | intent.putExtra(DownloadService.NOTICE_FILE_ID, fileInfo.id);
175 | intent.putExtra(DownloadService.NOTICE_PROGRESS, fileInfo.progress * 100 / fileInfo.length);
176 | context.sendBroadcast(intent);
177 | }
178 | return true;
179 | } else if(UPDATE_SUBTASK == msg.what) {
180 | ThreadInfo threadInfo = (ThreadInfo) msg.obj;
181 |
182 | SQLiteDatabase db = DBDownloadHelper.getInstance().getWritableDatabase(DBBaseHelper.SECRET_KEY);
183 | if(threadInfo.position == threadInfo.end + 1) {
184 | SQLiteUtils.getInstance().delete(db, DBDownloadHelper.TABLE_THREAD, "id = ? and fileId = ?", new String[]{threadInfo.id +"", threadInfo.fileId +""});
185 | } else {
186 | SQLiteUtils.getInstance().update(db, DBDownloadHelper.TABLE_THREAD, threadInfo.toContentValues(), "id = ? and fileId = ?", new String[]{threadInfo.id +"", threadInfo.fileId +""});
187 | }
188 | db.close();
189 |
190 | Debug.o(this, " fileId = " + threadInfo.fileId + " id = " + threadInfo.id
191 | + " position = " + threadInfo.position + " end = " + threadInfo.end);
192 | mCurrentThreadCount --;
193 | if(mCurrentThreadCount == 0) {
194 | isRunning = false;
195 |
196 | Intent intent = new Intent(context, DownloadService.class);
197 | intent.setAction(DownloadService.ACTION_UPDATE);
198 | intent.putExtra(DownloadService.FILE_INFO, fileInfo);
199 | context.startService(intent);
200 | }
201 |
202 | return true;
203 | }
204 |
205 | return false;
206 | }
207 | });
208 |
209 | class SubTask extends Thread {
210 | private ThreadInfo threadInfo;
211 | public SubTask(ThreadInfo threadInfo) {
212 | this.threadInfo = threadInfo;
213 | }
214 |
215 | @Override
216 | public void run() {
217 | if(isRunning) {
218 | HttpURLConnection conn = null;
219 | RandomAccessFile raf = null;
220 | try {
221 | //连接网络文件
222 | conn = HttpUtils.getInstance().createConnection(fileInfo.url);
223 | conn.setRequestMethod("GET");
224 | conn.setUseCaches(false);
225 | // conn.setRequestProperty("Accept-Encoding", "identity");//不采用gzip压缩
226 | // conn.setRequestProperty("Range", "bytes = " + threadInfo.position + "-" + threadInfo.end); // 坑爹,首先得服务端支持才行啊
227 | // Debug.o(this, " Range = " + conn.getRequestProperty("Range"));
228 | Debug.o(this, " Range = " + threadInfo.position + "-" + threadInfo.end);
229 |
230 | //获得文件长度
231 | int length = -1;
232 | int responseCode = conn.getResponseCode();
233 | if (/*responseCode == HttpURLConnection.HTTP_PARTIAL || */responseCode == HttpURLConnection.HTTP_OK) {
234 | length = conn.getContentLength();
235 | }
236 |
237 | // Debug.o(this, " " + Thread.currentThread().getName() + " responseCode : " + responseCode + " length = " + length);
238 |
239 | if(length > 0) {
240 |
241 | File tempFile = new File(DownloadService.DOWNLOAD_PATH + fileInfo.getFileName(true));
242 | raf = new RandomAccessFile(tempFile, "rwd");
243 | raf.seek(threadInfo.position); //seek()方法,在读写的时候跳过设置好的字节数,从下一个字节数开始读写
244 |
245 | InputStream is = conn.getInputStream();
246 | byte[] buffer = new byte[1024 * 4];
247 | int len = -1;
248 | boolean finish = false;
249 | long skip = threadInfo.position;
250 | long temp;
251 | while(isRunning && skip > 0) {
252 | temp = is.skip(skip);
253 | skip -= temp;
254 | }
255 | Debug.o(this, " skip : " + skip);
256 | while (isRunning && !finish && (len = is.read(buffer)) != -1) {
257 | //写入文件
258 | raf.write(buffer, 0, len);
259 |
260 | if(threadInfo.position + len > threadInfo.end) {
261 | len = (int) (threadInfo.end + 1 - threadInfo.position);
262 | finish = true;
263 | }
264 | threadInfo.position += len;
265 | Message msg = Message.obtain();
266 | msg.what = UPDATE_PROGRESS;
267 | msg.arg1 = len;
268 | mHandler.sendMessage(msg);
269 | }
270 | }
271 | } catch (Exception e) {
272 | e.printStackTrace();
273 | } finally {
274 | if(raf != null) {
275 | try {
276 | raf.close();
277 | } catch (Exception e) {}
278 | }
279 | if(conn != null) {
280 | conn.disconnect();
281 | }
282 |
283 | Message msg = Message.obtain();
284 | msg.what = UPDATE_SUBTASK;
285 | msg.obj = threadInfo;
286 | mHandler.sendMessage(msg);
287 | }
288 | }
289 | }
290 | }
291 | }
292 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/utils/DBBaseHelper.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.utils;
2 |
3 | import net.sqlcipher.database.SQLiteDatabase;
4 | import net.sqlcipher.database.SQLiteOpenHelper;
5 | import android.content.Context;
6 |
7 | public class DBBaseHelper extends SQLiteOpenHelper {
8 | /** SQLCipher所依赖的key,在对数据库进行加解密的时候SQLCipher都将使用这里指定的key。 */
9 | public static final String SECRET_KEY = "secret_key";
10 | protected static Context mContext;
11 | public static void init(Context context) {
12 | mContext = context;
13 | SQLiteDatabase.loadLibs(mContext);
14 | }
15 |
16 | protected DBBaseHelper(String name, int version) {
17 | super(mContext, name, null, version);
18 | }
19 |
20 | /**
21 | * 首次创建数据库的时候调用 一般可以把建库 建表的操作
22 | */
23 | @Override
24 | public void onCreate(SQLiteDatabase db) {
25 |
26 | Debug.o(this, " ================== onCreate");
27 | }
28 |
29 | /**
30 | * 当数据库的版本发生变化的时候 会自动执行
31 | */
32 | @Override
33 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
34 |
35 | Debug.o(this, " ================== onUpgrade");
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/utils/DBDownloadHelper.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.utils;
2 |
3 | import net.sqlcipher.database.SQLiteDatabase;
4 |
5 |
6 | public class DBDownloadHelper extends DBBaseHelper {
7 |
8 | /** 默认数据库版本 */
9 | public static final int DB_VERSION = 1;
10 |
11 | /** 默认数据库名字 */
12 | public static final String DB_DOWNLOAD = "downlod.db";
13 |
14 | /** 表名 */
15 | public static final String TABLE_FILE = "t_file";
16 |
17 | /** 创建表 */
18 | public static final String SQL_FILE = "create table if not exists " + TABLE_FILE + "("
19 | + "_id integer primary key autoincrement, "
20 |
21 | + "id integer not null, "
22 | + "url text not null, "
23 | + "progress text not null, "
24 | + "length text not null, "
25 |
26 | + "_extra1 text default(''), "
27 | + "_extra2 text default('')"
28 | + ")";
29 |
30 | /** 表名 */
31 | public static final String TABLE_THREAD = "t_thread";
32 |
33 | /** 创建表 */
34 | public static final String SQL_THREAD = "create table if not exists " + TABLE_THREAD + "("
35 | + "_id integer primary key autoincrement, "
36 |
37 | + "id integer not null, "
38 | + "fileId integer not null, "
39 | + "position text not null, "
40 | + "end text not null"
41 |
42 | + ")";
43 |
44 |
45 | private static DBDownloadHelper instance;
46 |
47 | public static DBDownloadHelper getInstance() {
48 | if(instance == null) {
49 | synchronized (DBDownloadHelper.class) {
50 | if(instance == null) {
51 | instance = new DBDownloadHelper(DB_DOWNLOAD, DB_VERSION);
52 | }
53 | }
54 | }
55 | return instance;
56 | }
57 |
58 | private DBDownloadHelper(String name, int version) {
59 | super(name, version);
60 | }
61 |
62 | @Override
63 | public void onCreate(SQLiteDatabase db) {
64 | super.onCreate(db);
65 |
66 | db.execSQL(SQL_FILE);
67 | db.execSQL(SQL_THREAD);
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/utils/Debug.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.utils;
2 |
3 | import android.util.Log;
4 |
5 |
6 | public class Debug {
7 | /** 测试开关,主要是LOG开关
8 | * 友盟LOG开关
9 | */
10 | public static boolean debug = true;
11 |
12 | public final static byte O = 0; //System.out
13 | public final static byte V = 1; //verbose
14 | public final static byte I = 2; //info
15 | public final static byte D = 3; //debug
16 | public final static byte W = 4; //warning
17 | public final static byte E = 5; //error
18 | public final static byte LOG = 6; //log.txt
19 | public final static byte NULL = 7; //no log
20 |
21 | private static byte model = O;
22 |
23 | //-------------------- System.out ------------------------------------------
24 | public static void o(Object tag, Object... s) {
25 | StringBuffer sb = new StringBuffer();
26 | for(Object ts:s) {
27 | sb.append(ts);
28 | }
29 | o(tag, sb.toString());
30 | }
31 | public static void o(Object tag, String s) {
32 | if(model <= O) {
33 | System.out.println((tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName())) + s);
34 | }
35 | }
36 |
37 | //-------------------- verbose ------------------------------------------
38 | public static void v(Object tag, Object... s) {
39 | StringBuffer sb = new StringBuffer();
40 | for(Object ts:s) {
41 | sb.append(ts);
42 | }
43 | v(tag, sb.toString());
44 | }
45 | public static void v(Object tag, String s) {
46 | if(model <= V) {
47 | Log.v(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s);
48 | }
49 | }
50 |
51 | //-------------------- debug --------------------------------------------
52 | public static void d(Object tag, Object... s) {
53 | StringBuffer sb = new StringBuffer();
54 | for(Object ts:s) {
55 | sb.append(ts);
56 | }
57 | d(tag, sb.toString());
58 | }
59 | public static void d(Object tag, String s) {
60 | if(model <= D) {
61 | Log.d(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s);
62 | }
63 | }
64 |
65 | //-------------------- info ---------------------------------------------
66 | public static void i(Object tag, Object... s) {
67 | StringBuffer sb = new StringBuffer();
68 | for(Object ts:s) {
69 | sb.append(ts);
70 | }
71 | i(tag, sb.toString());
72 | }
73 | public static void i(Object tag, String s) {
74 | if(model <= I) {
75 | Log.i(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s);
76 | }
77 | }
78 |
79 | //-------------------- warning ------------------------------------------
80 | public static void w(Object tag, Object... s) {
81 | StringBuffer sb = new StringBuffer();
82 | for(Object ts:s) {
83 | sb.append(ts);
84 | }
85 | w(tag, sb.toString());
86 | }
87 | public static void w(Object tag, String s) {
88 | w(tag, s, null);
89 | }
90 | public static void w(Object tag, String s, Throwable tr) {
91 | if(model <= W) {
92 | if(tr == null) {
93 | Log.w(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s);
94 | } else {
95 | Log.w(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s, tr);
96 | }
97 | }
98 | }
99 |
100 | //-------------------- error --------------------------------------------
101 | public static void e(Object tag, Object... s) {
102 | StringBuffer sb = new StringBuffer();
103 | for(Object ts:s) {
104 | sb.append(ts);
105 | }
106 | e(tag, sb.toString());
107 | }
108 | public static void e(Object tag, String s) {
109 | e(tag, s, null);
110 | }
111 | public static void e(Object tag, String s, Throwable tr) {
112 | if(model <= E) {
113 | if(tr == null) {
114 | Log.e(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s);
115 | } else {
116 | Log.e(tag==null ? "" : (tag instanceof String ? (String)tag : tag.getClass().getSimpleName()), s, tr);
117 | }
118 | }
119 | }
120 |
121 | //-------------------- log --------------------------------------------
122 | public static void log(Object tag, Object... s) {
123 | StringBuffer sb = new StringBuffer();
124 | for(Object ts:s) {
125 | sb.append(ts);
126 | }
127 | log(tag, sb.toString());
128 | }
129 | public static void log(Object tag, String s) {
130 | log(tag, s, null);
131 | }
132 | public static void log(Object tag, String s, Throwable tr) {
133 | e(tag, s, tr);
134 | }
135 |
136 |
137 | public static byte getModel() {
138 | return model;
139 | }
140 | public static void setModel(byte model) {
141 | Debug.model = model;
142 | }
143 |
144 | public static void setModel(String model) {
145 | if(model == null || model.trim().equalsIgnoreCase("")) {
146 | return;
147 | }
148 |
149 | byte bModel = O;
150 |
151 | if(model.equalsIgnoreCase("O")) {
152 | bModel = O;
153 | } else if(model.equalsIgnoreCase("V")) {
154 | bModel = V;
155 | } else if(model.equalsIgnoreCase("I")) {
156 | bModel = I;
157 | } else if(model.equalsIgnoreCase("D")) {
158 | bModel = D;
159 | } else if(model.equalsIgnoreCase("W")) {
160 | bModel = W;
161 | } else if(model.equalsIgnoreCase("E")) {
162 | bModel = E;
163 | } else if(model.equalsIgnoreCase("LOG")) {
164 | bModel = LOG;
165 | } else if(model.equalsIgnoreCase("NULL")) {
166 | bModel = NULL;
167 | }
168 |
169 | setModel(bModel);
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/utils/HttpUtils.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.utils;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.DataOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.InputStreamReader;
8 | import java.io.OutputStream;
9 | import java.net.HttpURLConnection;
10 | import java.net.URL;
11 | import java.security.KeyManagementException;
12 | import java.security.NoSuchAlgorithmException;
13 | import java.security.SecureRandom;
14 | import java.security.cert.X509Certificate;
15 |
16 | import javax.net.ssl.HostnameVerifier;
17 | import javax.net.ssl.HttpsURLConnection;
18 | import javax.net.ssl.SSLContext;
19 | import javax.net.ssl.SSLSession;
20 | import javax.net.ssl.TrustManager;
21 | import javax.net.ssl.X509TrustManager;
22 |
23 | import android.net.Uri;
24 | import android.os.Build;
25 | import android.util.Log;
26 |
27 | public class HttpUtils {
28 | protected static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
29 | protected static final String CHARSET = "UTF-8";
30 | /** 建立连接的超时时间 */
31 | protected static final int connectTimeout = 5 * 1000;
32 | /** 建立到资源的连接后从 input 流读入时的超时时间 */
33 | protected static final int readTimeout = 10 * 1000;
34 |
35 | private static HttpUtils instance;
36 |
37 | private TrustManager[] trustAllCerts = { new X509TrustManager() {
38 |
39 | public X509Certificate[] getAcceptedIssuers() {
40 | return null;
41 | }
42 |
43 | public void checkClientTrusted(X509Certificate[] certs, String authType) {
44 |
45 | }
46 |
47 | public void checkServerTrusted(X509Certificate[] certs, String authType) {
48 |
49 | }
50 | } };
51 |
52 | public static HttpUtils getInstance() {
53 | if (instance == null) {
54 | synchronized (HttpUtils.class) {
55 | if (instance == null) {
56 | instance = new HttpUtils();
57 | }
58 | }
59 | }
60 | return instance;
61 | }
62 |
63 | private HttpUtils() {
64 | try {
65 | HttpsURLConnection
66 | .setDefaultHostnameVerifier(new NullHostNameVerifier());
67 | SSLContext sc = SSLContext.getInstance("TLS");
68 | sc.init(null, trustAllCerts, new SecureRandom());
69 | HttpsURLConnection
70 | .setDefaultSSLSocketFactory(sc.getSocketFactory());
71 | } catch (KeyManagementException e) {
72 | e.printStackTrace();
73 | } catch (NoSuchAlgorithmException e) {
74 | e.printStackTrace();
75 | }
76 | }
77 |
78 | public HttpURLConnection createConnection(String url) throws IOException {
79 | String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
80 | HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl)
81 | .openConnection();
82 | conn.setConnectTimeout(connectTimeout);
83 | conn.setReadTimeout(readTimeout);
84 | return conn;
85 | }
86 |
87 | public InputStream getInputStream(String url) {
88 | InputStream is = null;
89 |
90 | try {
91 | HttpURLConnection conn = createConnection(url);
92 | conn.setRequestMethod("GET");
93 | is = conn.getInputStream();
94 | } catch (Exception e) {
95 | e.printStackTrace();
96 | }
97 |
98 | return is;
99 | }
100 |
101 | public String getString(String url) {
102 | String result = null;
103 | InputStream is = null;
104 | BufferedReader br = null;
105 | try {
106 | is = getInputStream(url);
107 | br = new BufferedReader(new InputStreamReader(is, CHARSET));
108 | String line = null;
109 | StringBuffer sb = new StringBuffer();
110 | while ((line = br.readLine()) != null) {
111 | sb.append(line);
112 | }
113 | result = sb.toString();
114 | } catch (IOException e) {
115 | e.printStackTrace();
116 | } finally {
117 | try {
118 | if (br != null) {
119 | br.close();
120 | }
121 | } catch (IOException e) {
122 | }
123 | try {
124 | if (is != null) {
125 | is.close();
126 | }
127 | } catch (IOException e) {
128 | }
129 | }
130 |
131 | return result;
132 | }
133 |
134 | public String postString(String url, String params) {
135 | String result = null;
136 | OutputStream os = null;
137 | InputStream is = null;
138 | BufferedReader br = null;
139 | try {
140 | HttpURLConnection conn = createConnection(url);
141 | conn.setRequestMethod("POST");
142 | conn.setDoOutput(true);
143 | conn.setDoInput(true);
144 | conn.setUseCaches(false);// POST方式不能缓存数据
145 | // conn.setRequestProperty(field, newValue);//header
146 |
147 | conn.setRequestProperty("Content-Type", "application/json; charset=" + CHARSET);
148 |
149 | // // 设置请求的头
150 | // conn.setRequestProperty("Connection", "keep-alive");
151 | // // 设置请求的头
152 | // conn.setRequestProperty("User-Agent",
153 | // "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
154 |
155 | if (params != null) {
156 | os = conn.getOutputStream();
157 | DataOutputStream dos = new DataOutputStream(os);
158 | dos.write(params.getBytes(CHARSET));
159 | dos.flush();
160 | dos.close();
161 | }
162 |
163 | is = conn.getInputStream();
164 | br = new BufferedReader(new InputStreamReader(is, CHARSET));
165 | String line = null;
166 | StringBuffer sb = new StringBuffer();
167 | while ((line = br.readLine()) != null) {
168 | sb.append(line);
169 | }
170 | result = sb.toString();
171 | } catch (IOException e) {
172 | e.printStackTrace();
173 | } finally {
174 | try {
175 | if (os != null) {
176 | os.close();
177 | }
178 | } catch (IOException e) {
179 | }
180 | try {
181 | if (br != null) {
182 | br.close();
183 | }
184 | } catch (IOException e) {
185 | }
186 | try {
187 | if (is != null) {
188 | is.close();
189 | }
190 | } catch (IOException e) {
191 | }
192 | }
193 |
194 | return result;
195 | }
196 |
197 | protected boolean shouldBeProcessed(HttpURLConnection conn)
198 | throws IOException {
199 | return conn.getResponseCode() == 200;
200 | }
201 |
202 | protected void disableConnectionReuseIfNecessary() {
203 | // HTTP connection reuse which was buggy pre-froyo
204 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
205 | System.setProperty("http.keepAlive", "false");
206 | }
207 | }
208 |
209 | private class NullHostNameVerifier implements HostnameVerifier {
210 | public NullHostNameVerifier() {
211 |
212 | }
213 |
214 | public boolean verify(String hostname, SSLSession session) {
215 | Log.i("RestUtilImpl", "Approving certificate for " + hostname);
216 | return true;
217 | }
218 | }
219 | }
220 |
--------------------------------------------------------------------------------
/src/com/kindy/httpurlconnection/utils/SQLiteUtils.java:
--------------------------------------------------------------------------------
1 | package com.kindy.httpurlconnection.utils;
2 |
3 | import net.sqlcipher.Cursor;
4 | import net.sqlcipher.database.SQLiteDatabase;
5 | import android.content.ContentValues;
6 |
7 | public class SQLiteUtils {
8 |
9 | private static SQLiteUtils instance;
10 |
11 | private SQLiteUtils() {
12 |
13 | }
14 |
15 | public static SQLiteUtils getInstance() {
16 | if(instance == null) {
17 | instance = new SQLiteUtils();
18 | }
19 |
20 | return instance;
21 | }
22 |
23 | /**
24 | * 查询
25 | * @param db
26 | * @param sql
27 | * @param selectionArgs
28 | * @return
29 | * Cursor 使用后请关闭
30 | */
31 | public Cursor rawQuery(SQLiteDatabase db, String sql, String[] selectionArgs) {
32 | Cursor cursor = null;
33 |
34 | try {
35 | cursor = db.rawQuery(sql, selectionArgs);
36 | } catch(Exception e) {
37 | Debug.e(this, " rawQuery : \n" + e.toString());
38 | }
39 |
40 | return cursor;
41 | }
42 |
43 | /** 插入 */
44 | public long insert(SQLiteDatabase db, String tableName, ContentValues values) {
45 | long rowId = -1;
46 |
47 | try {
48 | rowId = db.insert(tableName, null, values);
49 | } catch(Exception e) {
50 | Debug.e(this, " insert : \n" + e.toString());
51 | }
52 |
53 | return rowId;
54 | }
55 |
56 | /** 修改 */
57 | public int update(SQLiteDatabase db, String tableName, ContentValues values, String whereClause, String[] whereArgs) {
58 | int num = 0;
59 |
60 | try {
61 | num = db.update(tableName, values, whereClause, whereArgs);
62 | } catch(Exception e) {
63 | Debug.e(this, " update : \n" + e.toString());
64 | }
65 |
66 | return num;
67 | }
68 |
69 | /** 删除 */
70 | public int delete(SQLiteDatabase db, String tableName, String whereClause, String[] whereArgs) {
71 | int num = 0;
72 |
73 | try {
74 | num = db.delete(tableName, whereClause, whereArgs);
75 | } catch(Exception e) {
76 | Debug.e(this, " delete : \n" + e.toString());
77 | }
78 |
79 | return num;
80 | }
81 |
82 |
83 | //addColumn(db, tableName, "newColumn text not null default ('Kindy')")
84 | /** 增加列 */
85 | public void addColumn(SQLiteDatabase db, String tableName, String sql) {
86 | Cursor cursor = rawQuery(db, "alter table " + tableName + " add column " + sql, null);
87 | if(cursor != null) {
88 | cursor.close();
89 | }
90 | }
91 |
92 |
93 |
94 |
95 | public void showTables(SQLiteDatabase db) {
96 | try {
97 | Cursor cursor = rawQuery(db, "select * from sqlite_master where type in('table', 'view') order by name", null);
98 | // Cursor cursor = db.rawQuery("select name from sqlite_master where type='table' order by name", null);
99 | // Cursor cursor = db.rawQuery("select * from sqlite_master where type='table'", null);
100 | if(cursor!= null) {
101 | int num = 0;
102 | while(cursor.moveToNext()) {
103 | StringBuilder sb = new StringBuilder(" ============================ " + ++num);
104 | String[] names = cursor.getColumnNames();
105 | for(String name : names) {
106 | sb.append("\n").append(name).append(" : ").append(cursor.getString(cursor.getColumnIndex(name)));
107 | }
108 | Debug.o(this, sb.toString());
109 | }
110 | cursor.close();
111 | }
112 | } catch(Exception e) {
113 | Debug.e(this, " showTables : \n" + e.toString());
114 | }
115 | }
116 |
117 | public void showTableInfo(SQLiteDatabase db, String table) {
118 | try {
119 | Cursor cursor = rawQuery(db, "select * from " + table, null);
120 | if(cursor!= null) {
121 | int num = 0;
122 | while(cursor.moveToNext()) {
123 | StringBuilder sb = new StringBuilder(" ============================ " + table + " " + ++num);
124 | String[] names = cursor.getColumnNames();
125 | for(String name : names) {
126 | sb.append("\n").append(name).append(" : ").append(cursor.getString(cursor.getColumnIndex(name)));
127 | }
128 | Debug.o(this, sb.toString());
129 | }
130 | cursor.close();
131 | }
132 | } catch(Exception e) {
133 | Debug.e(this, " showTableInfo : \n" + e.toString());
134 | }
135 | }
136 |
137 |
138 | /**
139 | *
140 |
141 | 创建表 CREATE TABLE 表名 (列名 数据类型 限定符...)
142 | CREATE TABLE tTable (ID INTEGER,NAME TEXT);
143 |
144 | 修改表 ALTER TABLE ...(命令允许用户重命名或添加新的字段在已有表中,不能从表中删除字段。并且只能在表的末尾添加字段)
145 | 修改表名:ALTER TABLE 旧表名 RENAME TO 新表名
146 | ALTER TABLE tTable RENAME TO MyTable;
147 |
148 | 添加一列:ALTER TABLE 表名 ADD COLUMN 列名 数据类型 限定符 default (默认值)
149 | ALTER TABLE MyTable ADD COLUMN AGE INTEGER default (0);
150 |
151 | 删除表 DROP TABLE 表名
152 | DROP TABLE MyTable;
153 |
154 |
155 | db.execSQL("create table if not exists stutb("
156 | + "_id integer primary key autoincrement,"
157 | + "name text not null,"
158 | + "sex text not null,"
159 | + "age integer not null)");
160 | db.execSQL("insert into stutb(name,sex,age)values('张三','女',999)");
161 |
162 | for(int i=0; i<10; i++) {
163 | ContentValues values = new ContentValues();
164 | values.put("name", "张三");
165 | values.put("sex", "男");
166 | values.put("age", i);
167 | long rowId = db.insert("stutb", null, values);
168 | Debug.o(this, " rowId : " + rowId);
169 | }
170 |
171 |
172 |
173 | Cursor c = db.rawQuery("select * from stutb", null);
174 |
175 | db.update("stutb", values, "_id>?", new String[]{"3"});//将全部id>3的人的性别改成女
176 | db.delete("stutb", "name like ?", new String[]{"%丰%"});//删除所有名字中带有丰的人
177 |
178 | Cursor c = db.query("stutb", null, "_id>?", new String[]{"0"}, null,
179 | null, //DESC/ASC:降序/升序(格式是String orderBy = "_id desc")
180 | "name");
181 |
182 |
183 | "select * from stutb limit " + 跳过多少条记录 +", " + 要显示多少条记录
184 | "select * from stutb limit 0, 3"
185 |
186 | 分页查询
187 | Cursor c = db.rawQuery("select * from stutb where age > 3 order by age asc limit 2 offset 0", null);
188 | 通用公试: sql = "select * from FlyCrocodile where "+条件+" order by "+排序+" limit "+要显示多少条记录+" offset "+跳过多少条记录
189 | */
190 | }
--------------------------------------------------------------------------------