您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在Android中利用Handler實(shí)現(xiàn)一個文件下載功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
代碼實(shí)現(xiàn)
在AndroidManifest.xml文件中聲明申請的權(quán)限,如下所示:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
新建一個名為DownloadDemo的項(xiàng)目,activity_main.xml代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="下載" /> <ProgressBar android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:max="100" android:progress="0" /> </LinearLayout>
MainActivity.class代碼如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String APP_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk"; public static final int DOWNLOAD_MESSAGE_CODE = 100001; private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002; public static final int REQUEST_CODE = 1; private Button button; private ProgressBar progressBar; private MyHandler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); askPermission(); mHandler = new MyHandler(this); } public static class MyHandler extends Handler { final WeakReference<MainActivity> mWeakReference; public MyHandler(MainActivity activity) { this.mWeakReference = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { MainActivity activity = mWeakReference.get(); super.handleMessage(msg); switch (msg.what) { case DOWNLOAD_MESSAGE_CODE: activity.progressBar.setProgress((Integer) msg.obj); if (((Integer) msg.obj) == 100) { Toast.makeText(activity, "文件下載已完成!", Toast.LENGTH_SHORT).show(); } break; case DOWNLOAD_MESSAGE_FAIL_CODE: Toast.makeText(activity, "文件下載失??!", Toast.LENGTH_SHORT).show(); break; } } } /** * 申請權(quán)限 */ private void askPermission() { //將所需申請的權(quán)限添加到List集合中 List<String> permissionList = new ArrayList<>(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } //判斷權(quán)限列表是否為空,若不為空,則向用戶申請權(quán)限,否則則直接執(zhí)行操作 if (!permissionList.isEmpty()) { String[] permissions = permissionList.toArray(new String[permissionList.size()]); ActivityCompat.requestPermissions(MainActivity.this, permissions, REQUEST_CODE); } else { //TODO button.setOnClickListener(this); } } /** * 用戶對請求權(quán)限的dialog做出響應(yīng)之后,會處理請求權(quán)限的響應(yīng) * * @param requestCode 請求碼 * @param permissions 權(quán)限的集合 * @param grantResults 權(quán)限授予的結(jié)果 */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE: if (grantResults.length > 0) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "必須同意所有權(quán)限才能使用本程序", Toast.LENGTH_SHORT).show(); finish(); return; } } //TODO button.setOnClickListener(this); } else { Toast.makeText(this, "權(quán)限申請失?。?quot;, Toast.LENGTH_SHORT).show(); finish(); } break; default: break; } } /** * 點(diǎn)擊事件 * * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: new Thread(new Runnable() { @Override public void run() { download(APP_URL); } }).start(); break; } } /** * 下載 * * @param appUrl */ private void download(String appUrl) { try { //實(shí)例化一個url對象 URL url = new URL(appUrl); //獲取URLConnection對象 URLConnection urlConnection = url.openConnection(); //獲取輸入流 InputStream inputStream = urlConnection.getInputStream(); //獲取文件的總長度 int contentLength = urlConnection.getContentLength(); //設(shè)置軟件下載到手機(jī)存儲的位置文件夾名稱 String downloadFolderName = Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator; File file = new File(downloadFolderName); //若文件夾不存在則進(jìn)行創(chuàng)建 if (!file.exists()) { file.mkdir(); } String fileName = downloadFolderName + "chaixingsi.apk"; File apkFile = new File(fileName); if (apkFile.exists()) { apkFile.delete(); } int downloadContentLength = 0; int length = 0; byte[] bytes = new byte[1024]; OutputStream outputStream = new FileOutputStream(fileName); while ((length = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, length); downloadContentLength += length; /** * 發(fā)送消息通知主線程去更新UI */ Message message = Message.obtain(); message.obj = downloadContentLength * 100 / contentLength; message.what = DOWNLOAD_MESSAGE_CODE; mHandler.sendMessage(message); } inputStream.close(); outputStream.close(); } catch (MalformedURLException e) { //下載失敗的話也發(fā)送消息 notifyDownloadFailed(); e.printStackTrace(); } catch (IOException e) { notifyDownloadFailed(); e.printStackTrace(); } } /** * 通知下載失敗 */ private void notifyDownloadFailed() { Message message = Message.obtain(); message.what = DOWNLOAD_MESSAGE_FAIL_CODE; mHandler.sendMessage(message); } /** * 初始化視圖 */ private void initView() { button = findViewById(R.id.button); progressBar = findViewById(R.id.progressBar); } }
關(guān)于怎么在Android中利用Handler實(shí)現(xiàn)一個文件下載功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。