Android07-网络编程(二)

1.get和post从服务端请求数据

public class MainActivity extends Activity {

    private EditText et_username;
	private EditText et_password;
	private String path = "http://192.168.43.21:8080/login";


	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        
    }

    
    public void login(final View view){
    	new Thread(){
    		public void run() {
    			String username = et_username.getText().toString();
    			String password = et_password.getText().toString();
    			
    			
    			try {
    				if(view.getId() == R.id.btn_login){
    					//拼接get请求
            			//如果提交的参数是中文,需要进行url编码
            			String spec = path + "?username=" + 
            					URLEncoder.encode(username, "utf-8") + "&password=" + 
            					URLEncoder.encode(password,"utf-8");
    					URL url = new URL(spec);
    					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    					connection.setRequestMethod("GET");
    					connection.setConnectTimeout(10000);
    					int code = connection.getResponseCode();
    					if(code == 200){
    						String result = Utils.getStringFromStream(connection.getInputStream());
    						//在子线程中要操作UI,对于简单的业务,可以使用runOnUiThread
    						showToast(result);
    					}
    				}else if(view.getId() == R.id.btn_loginToPost){
    					//处理post请求
            			//如果提交的参数是中文,需要进行url编码 请求体,浏览器直接输入url带中文,自动进行编码
            			String params = "username=" + 
            					URLEncoder.encode(username, "utf-8") + "&password=" + 
            					URLEncoder.encode(password,"utf-8");
    					URL url = new URL(path);
    					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    					connection.setRequestMethod("POST");
    					connection.setConnectTimeout(10000);
    					
    					//设置要传递的数据类型
    					connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    					//告诉服务器,传递的数据长度
    					connection.setRequestProperty("Content-Length", String.valueOf(params.length()));
    					//打开输出流
    					connection.setDoOutput(true);
    					//通过流将数据发送到 服务端
    					connection.getOutputStream().write(params.getBytes());
    					int code = connection.getResponseCode();
    					if(code == 200){
    						String result = Utils.getStringFromStream(connection.getInputStream());
    						//在子线程中要操作UI,对于简单的业务,可以使用runOnUiThread
    						showToast(result);
    					}
    				}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    			
    		}
    	}.start();
    }
    
    private void showToast(final String str){
    	runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
			}
		});
    }
}

2.使用HttpClient进行get和post访问数据

public class MainActivity extends Activity {

	private String path = "http://192.168.43.21:8080/login";
    private EditText et_username;
	private EditText et_password;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        
        Button btn_login = (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(new MyListener());
        Button btn_loginPost = (Button) findViewById(R.id.btn_loginPost);
        btn_loginPost.setOnClickListener(new MyListener());
    }
    
    
	private class MyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.btn_login){
				new Thread(){
					
					@Override
					public void run() {
						System.out.println("kk");
						String username = et_username.getText().toString();
						String password = et_password.getText().toString();
						
						String uri = path + "?username=" + username + "&password=" + password;
						//get方式的请求
						DefaultHttpClient httpClient = new DefaultHttpClient();
						//封装get请求的路径和所需要携带的数据
						HttpGet httpGet = new HttpGet(uri);
						System.out.println(uri);
						try {
							//执行get请求,并返回响应
							HttpResponse httpResponse = httpClient.execute(httpGet);
							//获取HttpResponse中封装的响应的状态码
							StatusLine statusLine = httpResponse.getStatusLine();
							int code = statusLine.getStatusCode();
							if(code == 200){
								//获取响应结果的流对象
								HttpEntity entity = httpResponse.getEntity();
								InputStream inputStream = entity.getContent();
								String result = Utils.getStringFromStream(inputStream);
								showToast(result);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					}
					
				}.start();
			}else if(v.getId() == R.id.btn_loginPost){
				new Thread(){
					
					public void run() {
						System.out.println("post");
						String username = et_username.getText().toString();
						String password = et_password.getText().toString();
						
						//使用BasicNameValuePair封装Post请求体
						BasicNameValuePair valuePair1 = new BasicNameValuePair("username",username);
						BasicNameValuePair valuePair2 = new BasicNameValuePair("password", password);
						
						List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
						list.add(valuePair1);
						list.add(valuePair2);
						
						try {
							
							UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"utf-8");
							
							//封装post请求的路径和数据
							HttpPost httpPost = new HttpPost(path);
							httpPost.setEntity(formEntity);
							
							DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
							//执行post请求
							HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
							//获取响应码
							int code = httpResponse.getStatusLine().getStatusCode();
							if(code == 200){
								//获取响应结果的流对象
								HttpEntity entity = httpResponse.getEntity();
								InputStream inputStream = entity.getContent();
								String result = Utils.getStringFromStream(inputStream);
								showToast(result);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}.start();
			}
		}
		
	}
	
	private void showToast(final String str){
    	runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
			}
		});
    }
}

3.使用第三方框架进行get和post请求

public class MainActivity extends Activity {

	private String path = "http://192.168.43.21:8080/login";
    private EditText et_password;
	private EditText et_username;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        
        Button btn_login = (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println("get--");
				String username = et_username.getText().toString();
				String password = et_password.getText().toString();
				
				String url = path + "?username=" + username + "&password=" + password;
				//异步从网络获取数据
				AsyncHttpClient httpClient = new AsyncHttpClient();
				
				//AsyncHttpResponseHandler用于对响应结果进行处理
				httpClient.get(url, new AsyncHttpResponseHandler() {
					
					@Override
					public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
						if(statusCode == 200){
							try {
								showToast(new String(responseBody,"utf-8"));
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					
					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						// TODO Auto-generated method stub
						
					}
				});
			}
		});
        
        Button btn_loginPost = (Button) findViewById(R.id.btn_loginPost);
        btn_loginPost.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println("post--");
				String username = et_username.getText().toString();
				String password = et_password.getText().toString();
				
				AsyncHttpClient httpClient = new AsyncHttpClient();
				//使用Map封装参数
				Map<String,String> map = new HashMap<String,String>();
				map.put("username", username);
				map.put("password", password);
				
				//RequestParams封装Map中key,value形式的参数
				RequestParams requestParams = new RequestParams(map);
				httpClient.post(path, requestParams, new AsyncHttpResponseHandler() {
					
					@Override
					public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
						if(statusCode == 200){
							try {
								showToast(new String(responseBody,"utf-8"));
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					
					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						// TODO Auto-generated method stub
						
					}
				});
			}
		});
    }
	
	private void showToast(final String str){
    	runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
			}
		});
    }
}

4.多线程下载

1:突破服务端对单个线程速度的限制。
2:无法突破带宽的限制。

5.多线程下载原理代码

public class MainMoreThread {

	public static void main(String[] args) {
		String path = "http://127.0.0.1:8080/img/news.xml";
		try {
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(10000);
			//使用Range属性确确定要接受的文件字节的范围
			connection.setRequestProperty("Range", "bytes=0-20");
			//使用Range获取一个范围的数据成功之后,返回的状态码应该是206
			if(connection.getResponseCode() == 206){
				InputStream inputStream = connection.getInputStream();
				String result = Utils.getStringFromStream(inputStream);
				System.out.println(result);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

6.多线程下载代码

//主要进行每一个线程下载的范围,设置Range保证范围数据的读取
public class MoreThreadDownload {

	private static String spec = "http://127.0.0.1:8080/img/news.xml";
	private static int threadCount = 3;
	
	public static void main(String[] args) {
		try {
			URL url = new URL(spec);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(10000);
			int responseCode = connection.getResponseCode();
			if(responseCode == 200){
				//获取文件内容长度
				int length = connection.getContentLength();
				//在本地创建一个同样打的文件,第一个参数是文件名,第二个参数,rw,打开,可以进行读取和写入
				RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
				raf.setLength(length);
				
				//计算每一个线程下载文件的范围
				for(int i = 0;i < threadCount;i++){
					int n = length / threadCount;
					int start = i * n;
					int end = (i + 1) * n - 1;
					if(i == threadCount){
						end = length - 1;
					}
					
					new DownloadThread(start, end, i).start();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private static class DownloadThread extends Thread {
		
		private int startIndex;
		private int endIndex;
		private int threadId;
		
		
		public DownloadThread(int startIndex, int endIndex, int threadId) {
			super();
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.threadId = threadId;
		}


		public void run() {
			try {
				URL url = new URL(spec);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setRequestMethod("GET");
				connection.setReadTimeout(10000);
				//设置请求的Range头,确定每一个线程下载的范围
				connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
				if(connection.getResponseCode() == 206){
					System.out.println("文件开始下载" + threadId + "-" + startIndex + "-" + endIndex);
					InputStream inputStream = connection.getInputStream();
					//使用RandomAccessFile主要是为了在多线程文件追加是方便
					//原理是知道文件的总大小,对于0,1,2三个线程,如果2线程首先完成下载
					//0,1线程准备使用的空间,不会被占用,只是预留,等到三个线程都完成下载,则文件下载完成
					RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
					//确定文件从startIndex出开始追加,不然会进行文件的覆盖
					raf.seek(startIndex);
					int len = 0;
					byte[] bytes = new byte[1024];
					while((len = inputStream.read(bytes)) != -1){
						raf.write(bytes,0,len);
					}
					raf.close();
					System.out.println("下载结束");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public static String getFileName(String spec){
		String[] strs = spec.split("/");
		return strs[strs.length - 1];
	}
}

7.断点续传

//主要就是记录每次下载到的文件的索引,然后利用RandomAccessFile的rwd模式
//就是的将这个索引保存在磁盘上,然后需要在设置Range头的时候,
//先进行索引的读入,如果有文件数据,说明上一次下载了一部分,
//就从上次的位置开始下载
public class MoreThreadDownload {

	private static String spec = "http://127.0.0.1:8080/img/news.xml";
	private static int threadCount = 3;
	
	public static void main(String[] args) {
		try {
			URL url = new URL(spec);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(10000);
			int responseCode = connection.getResponseCode();
			if(responseCode == 200){
				//获取文件内容长度
				int length = connection.getContentLength();
				//在本地创建一个同样打的文件,第一个参数是文件名,第二个参数是文件的权限,rw,读写权限
				RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
				raf.setLength(length);
				
				//计算每一个线程下载文件的范围
				for(int i = 0;i < threadCount;i++){
					int n = length / threadCount;
					int start = i * n;
					int end = (i + 1) * n - 1;
					if(i == threadCount){
						end = length - 1;
					}
					
					new DownloadThread(start, end, i).start();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private static class DownloadThread extends Thread {
		
		private int startIndex;
		private int endIndex;
		private int threadId;
		
		
		public DownloadThread(int startIndex, int endIndex, int threadId) {
			super();
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.threadId = threadId;
		}


		public void run() {
			try {
				
				//读取上一个线程断点出的文件索引,以便从断点出开始下载
				File f = new File(getFileName(spec) + threadId + ".log");
				if(f != null && f.length() > 0){
					System.out.println("11111");
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
					String line = br.readLine();
					startIndex = Integer.parseInt(line);
				}
				
				URL url = new URL(spec);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setRequestMethod("GET");
				connection.setReadTimeout(10000);
				//设置请求的Range头,确定每一个线程下载的范围
				connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
				if(connection.getResponseCode() == 206){
					System.out.println("文件开始下载" + threadId + "-" + startIndex + "-" + endIndex);
					InputStream inputStream = connection.getInputStream();
					//使用RandomAccessFile主要是为了在多线程文件追加是方便
					//原理是知道文件的总大小,对于0,1,2三个线程,如果2线程首先完成下载
					//0,1线程准备使用的空间,不会被占用,只是预留,等到三个线程都完成下载,则文件下载完成
					RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
					//确定文件从startIndex出开始追加,不然会进行文件的覆盖
					raf.seek(startIndex);
					int len = 0;
					byte[] bytes = new byte[1024];
					//使用count记录下载成功的字节数
					int count = 0;
					while((len = inputStream.read(bytes)) != -1){
						raf.write(bytes,0,len);
						count += len;
						//position记录具体的位置,要将具体的位置进行磁盘存储,保证下一次可以正常使用
						int position = startIndex + count;
						//position占用空间很小,磁盘在存储的使用会有缓冲,使用rwd模式,保证及时将position刷新在磁盘
						RandomAccessFile file = new RandomAccessFile(getFileName(spec) + threadId + 
								".log", "rwd");
						
						file.write(String.valueOf(position).getBytes());
					}
					raf.close();
					System.out.println("下载结束");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public static String getFileName(String spec){
		String[] strs = spec.split("/");
		return strs[strs.length - 1];
	}
}

8.Android完成多线程下载和断点续传

public class MainActivity extends Activity implements OnClickListener {

    private EditText ed_url;
	private EditText ed_threadCount;
	private Button btn_download;
	private LinearLayout ll_progess;
	
	private String spec = "http://10.0.2.2:8080/img/news.xml";
	private int threadCount = 3;
	//每一个进程应该下载的数据的大小
	private int n;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ed_url = (EditText) findViewById(R.id.et_url);
        ed_threadCount = (EditText) findViewById(R.id.et_threadCount);
        btn_download = (Button) findViewById(R.id.btn_download);
        ll_progess = (LinearLayout) findViewById(R.id.ll_progress);
        
        btn_download.setOnClickListener(this);
    }
	
	@Override
	public void onClick(View v) {
		//在加载进度条之前清空LinearLayout,防止用户对此点击,出现多个进度条
    	ll_progess.removeAllViews();
    	//加载进度条
    	String temp = ed_threadCount.getText().toString().trim();
    	threadCount = Integer.parseInt(temp);
    	for(int i = 0;i < threadCount;i++){
    		View.inflate(getApplicationContext(), R.layout.item, ll_progess);
    	}
    	
    	//子线程进行联网操作
    	new Thread(){
    		public void run() {
    			try {
        			URL url = new URL(spec);
        			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        			connection.setRequestMethod("GET");
        			connection.setConnectTimeout(10000);
        			int responseCode = connection.getResponseCode();
        			if(responseCode == 200){
        				//获取文件内容长度
        				int length = connection.getContentLength();
        				//在本地创建一个同样打的文件,第一个参数是文件名,第二个参数是文件的权限,rw,读写权限
        				RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
        				raf.setLength(length);
        				
        				//计算每一个线程下载文件的范围
        				for(int i = 0;i < threadCount;i++){
        					n = length / threadCount;
        					int start = i * n;
        					int end = (i + 1) * n - 1;
        					if(i == threadCount){
        						end = length - 1;
        					}
        					
        					//设置进度条的最大进度
        					ProgressBar progressBar = (ProgressBar) ll_progess.getChildAt(i);
        					progressBar.setMax(end - start);
        					new DownloadThread(start, end, i).start();
        				}
        			}
        		} catch (Exception e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
    		}
    	}.start();
	}
	
	private  class DownloadThread extends Thread {
		
		private int startIndex;
		private int endIndex;
		private int threadId;
		private ProgressBar progressBar;
		
		
		public DownloadThread(int startIndex, int endIndex, int threadId) {
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.threadId = threadId;
			progressBar = (ProgressBar) ll_progess.getChildAt(threadId);
		}


		public void run() {
			try {
				
				//读取上一个线程断点出的文件索引,以便从断点出开始下载
				File f = new File(getFileName(spec) + threadId + ".log");
				if(f != null && f.length() > 0){
					System.out.println("11111");
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
					String line = br.readLine();
					startIndex = Integer.parseInt(line);
				}
				
				URL url = new URL(spec);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setRequestMethod("GET");
				connection.setReadTimeout(10000);
				//设置请求的Range头,确定每一个线程下载的范围
				connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
				if(connection.getResponseCode() == 206){
					InputStream inputStream = connection.getInputStream();
					//使用RandomAccessFile主要是为了在多线程文件追加是方便
					//原理是知道文件的总大小,对于0,1,2三个线程,如果2线程首先完成下载
					//0,1线程准备使用的空间,不会被占用,只是预留,等到三个线程都完成下载,则文件下载完成
					RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
					//确定文件从startIndex出开始追加,不然会进行文件的覆盖
					raf.seek(startIndex);
					int len = 0;
					byte[] bytes = new byte[1024];
					//使用count记录下载成功的字节数
					int count = 0;
					while((len = inputStream.read(bytes)) != -1){
						raf.write(bytes,0,len);
						count += len;
						//position记录具体的位置,要将具体的位置进行磁盘存储,保证下一次可以正常使用
						int position = startIndex + count;
						//position占用空间很小,磁盘在存储的使用会有缓冲,使用rwd模式,保证及时将position刷新在磁盘
						RandomAccessFile file = new RandomAccessFile(getFileName(spec) + threadId + 
								".log", "rwd");
						
						file.write(String.valueOf(position).getBytes());
						
						//每次写入完成之后,更改进度条的进度
						//ProgressBar是一个耗时的操作,可以在子线程中进行UI的修改,底层实现的主线程中修改UI
						progressBar.setProgress(position - threadId * n);
					}
					raf.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public String getFileName(String spec){
		String[] strs = spec.split("/");
		return getCacheDir().getAbsolutePath() + "/" + strs[strs.length - 1];
	}
}
<!-- UI界面 -->
<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:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入url" />

    <EditText
        android:id="@+id/et_threadCount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入线程数" />
    
    <Button
        android:id="@+id/btn_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="下载" />
    
    <LinearLayout
        android:id="@+id/ll_progress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        
    </LinearLayout>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@android:style/Widget.ProgressBar.Horizontal" >
    
</ProgressBar>

9.使用开源项目实现文件上传

public class MainActivity extends Activity {

    private ProgressBar pb;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button btn_download = (Button) findViewById(R.id.btn_download);
        pb = (ProgressBar) findViewById(R.id.pb);
        
        btn_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				HttpUtils httpUtils = new HttpUtils();
				String url = "http://10.0.2.2:8080/img/news.xml";
				//第一个参数要下载文件的url
				//第二个参数要存储的地方
				//第三个参数是否支持断点续传
				//第四个参数回调
				httpUtils.download(url, getFileName(url), true,new RequestCallBack<File>() {
					
					@Override
					public void onSuccess(ResponseInfo<File> responseInfo) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						pb.setMax((int)total);
						pb.setProgress((int)current);
					}
				});
			}
		});
    }
    
    private String getFileName(String path) {
		String[] result = path.split("/");
		return getCacheDir().getAbsolutePath()+"/"+result[result.length-1];
	}

}

10.getApplicationContext()

1:getApplicationContext()的获取应用的应用的上下文,生命周期比较长,在使用时比较安全。
2:如果使用Activity作为上下文环境,可能出现内存泄露的问题,所以在大多数的情况下,应该使用getApplicationContext()做为上下文环境,但是在操作对话框的使用,应该使用Activity。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值