public class MainActivity extends AppCompatActivity { private Button button; private NumberProgressBar bar; private int filesize; private boolean isDown; private int mCruuDownsize=0; private int mCurrProgress = -1; private File file; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); bar.setProgress(mCurrProgress); if(mCurrProgress==100) { isDown = false; mCruuDownsize=0; filesize=0; mCurrProgress=-1; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); bar = (NumberProgressBar) findViewById(R.id.numbar); file = new File(getExternalCacheDir(),"jinritoutiao.apk"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (button.getText().equals("下载")){ loatHttp(); button.setText("暂停"); }else if (button.getText().equals("暂停")){ stopDown(); button.setText("下载"); } } }); } private void stopDown() { isDown=false; } public void loatHttp(){ if(isDown) return; new Thread(){ @Override public void run() { super.run(); try { URL url = new URL("http://gdown.baidu.com/data/wisegame/038d77c9af95d110/jinritoutiao_627.apk"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = 200; if(filesize!=0) { connection.setRequestProperty("Range", "bytes=" + mCruuDownsize + "-" + filesize); responseCode=206; }else{ filesize=connection.getContentLength(); } if (connection.getResponseCode()==responseCode){ InputStream inputStream = connection.getInputStream(); RandomAccessFile raf =new RandomAccessFile(file,"rw"); raf.seek(mCruuDownsize); byte[] arr = new byte[1024]; int len = -1; while (isDown && (len = inputStream.read(arr))!=-1){ raf.write(arr,0,len); mCruuDownsize+=len; int pro = (int)(mCruuDownsize*100L/filesize); if (pro!=mCurrProgress){ handler.sendEmptyMessage(0); mCurrProgress=pro; } } raf.close(); } } catch (Exception e) { e.printStackTrace(); } } }.start(); isDown= true; }