利用近期学习的知识做一个下载器,输入网址即可下载的下载器。
首先复习上节课的知识。
多线程的那些事:
->何为线程,多线程?
->为什么要使用多线程?
帮助提高效率,耗时操作并行。多线程可防止一条线卡死。
->ANR(Application Not Responding)
->什么时候使用多线程?
->Android当中的多线程。
总结来说:线程就相当于做饭的过程,OnCreate一步一步按顺序执行:摘菜->洗菜->切菜->做菜->吃菜。 电饭锅相当于另外一个线程,帮做米饭,同时你吃菜,电饭锅会在蒸熟米饭后语音或其他方式提醒。
如何使用多线程?
->Main/UI Thread和Worker Thread。
->Main/UI Thread和Worker Thread之间的通信。
->Thread/Runnable.
->线程安全
->Activity.runOnUiThread(Runnable)
->View.post(Runnable)
->View.post Delayed(Runnable,long)
->Handler
->Async Task
->同步代码块(Synchronized block).
下载器的制作方法:
在activity_main.xml文件中做好下载器的下载界面:
下载按钮:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/download"
android:id="@+id/download_button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
输入网址的文本框:
<EditText
android:layout_width="400dp"
android:layout_height="50dp"
android:id="@+id/EditText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="84dp" />
进度条:
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:max="100"
android:layout_below="@+id/download_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="72dp" />
进度更新显示:
<TextView
android:id="@+id/text_view"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text=" "
android:textColor="@color/blue"
android:layout_below="@+id/progressBar"
android:layout_alignRight="@+id/download_button"
android:layout_alignEnd="@+id/download_button" />
输入网址提示:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="请输入网址:"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
在MainActivity.java文件中:
public class MainActivity extends Activity implements View.OnClickListener{
public static final String GEEK_BAND = "RENHONG";
private Handler mHandler = new DownloadHandler(this);
private TextView mTextView;
private Button mDownloadButton;
private ProgressBar mProgressBar;
private EditText mEditText;
public TextView getmTextView() {
return mTextView;
}
public ProgressBar getmProgressBar() {
return mProgressBar;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_view);
mEditText=(EditText) findViewById(R.id.EditText);
mDownloadButton = (Button) findViewById(R.id.download_button);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDownloadButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.download_button:
String apkurl=mEditText.getText().toString();
new TestTask().execute(apkurl);
break;
}
}
class TestTask extends AsyncTask<String,Integer,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String...prams) {
try {
URL url = new URL(prams[0]);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
int contentLength = urlConnection.getContentLength();
// 要下载的文件的大小
String downloadFoldersName = Environment.getExternalStorageDirectory() + File.separator + GEEK_BAND + File.separator;
File file = new File(downloadFoldersName);
if(!file.exists()){
file.mkdir();
}
String fileName = downloadFoldersName + "test.apk";
File apkFile = new File(fileName);
if(apkFile.exists()){
apkFile.delete();
}
int downloadSize = 0;
byte[] bytes = new byte[1024];
int length = 0;
OutputStream outputStream = new FileOutputStream(fileName);
while ((length = inputStream.read(bytes)) != -1){
outputStream.write(bytes, 0, length);
downloadSize += length;
int progress = downloadSize * 100/ contentLength;
Message message = mHandler.obtainMessage();
message.obj = progress;
message.what = 0;
mHandler.sendMessage(message);
}
inputStream.close();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public static class DownloadHandler extends Handler{
public final WeakReference<MainActivity>mActivity;
public DownloadHandler(MainActivity activity){
mActivity = new WeakReference<>(activity);
}
public void handleMessage(Message msg){
super.handleMessage(msg);
MainActivity activity = mActivity.get();
switch (msg.what){
case 0:
int progress = (int)msg.obj;
activity.getmProgressBar().setProgress(progress);
activity.getmTextView().setText("已下载:"+progress);
if (progress == 100){
Toast.makeText(activity,"下载完成",Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
在Mainifest.xml文件中注册网络:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.INTERNET" />