您的位置:首页 > 职场人生

面试题 -- 下载并安装APK

2016-07-02 11:25 162 查看

面试题 – 下载并安装APK

任务:

下载一个apk文件,并显示下载的速度、进度百分比、下载用时时间,并且下载完毕后,自动安装apk


布局文件:一个进度条,一个文本,一个按钮

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="@id/progressBar"
android:text="Medium Text" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerHorizontal="true"
android:onClick="startDownLoad"
android:text="Start DownLoad" />
</RelativeLayout>


DownLoadActivity:负责下载的控制与显示

public class DownLoadActivity extends AppCompatActivity {
private static final String QQMusicUri = "http://dldir1.qq.com/music/clntupate/QQMusic.apk";

private ProgressBar progressBar;
private TextView downloadingInfo;
private Button downloadButton;
final String fileName = "QQMusic.apk";

public static final String rootDirectory = Environment.getExternalStorageDirectory().getPath() + "/Download";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int speed = (int) msg.obj;
int percent = msg.arg1;
int userTime = msg.arg2;

downloadingInfo.setText(speed + "KB/S  " + percent + "% "
+ formatTime(userTime));
downloadButton.setClickable(false);
if (percent == 100) {
Toast.makeText(MainActivity.this, "Download Finished", Toast.LENGTH_SHORT).show();
downloadButton.setClickable(true);
}
}
};

/**
* 格式化时间
*/
public static String formatTime(int time) {
if (time < 60) {
return time + "s";
} else {
return time / 60 + "min" + time % 60 + "s";
}
}

/**
* 初始化控件
*/
private void initViews() {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
downloadingInfo = (TextView) findViewById(R.id.textView);
downloadButton = (Button) findViewById(R.id.button);
}

/**
* 开始下载
*/
public void startDownLoad(View view) {
downloadButton.setText("Stop DownLoad");
Toast.makeText(this, rootDirectory, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
installApk(downloadFile());
}
}).start();
}

/**
* 安装APK
*
* @param file
*/
public void installApk(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}

/**
* 下载文件
*/
public File downloadFile() {
File tempFile = new File(rootDirectory);
if (!tempFile.exists()) {
tempFile.mkdir();
}
File file = new File(tempFile + "/" + fileName);
return HttpRequestUtils.downLoad(file, QQMusicUri, mHandler,progressBar);
}
}


下载工具类:

public class HttpRequestUtils {
/**
* 下载
*
* @param file
* @param urlStr 下载地址
* @return
*/
public static File downLoad(File file, String urlStr, Handler handler,ProgressBar progressBar) {
HttpURLConnection connection = null;
FileOutputStream fos = null;
InputStream is = null;
try {
URL url = new URL(urlStr);
//创建HttpURLConnection对象
connection = (HttpURLConnection) url.openConnection();

//配置参数
//允许输入,默认为false
connection.setDoOutput(true);
//允许输出,默认为true
connection.setDoInput(true);
//设为POST请求,默认为GET
connection.setRequestMethod("POST");
//设置连接超时
connection.setConnectTimeout(20 * 1000);
//设置读取数据超时
connection.setReadTimeout(20 * 1000);

//连接
connection.connect();

if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int totalSize = connection.getContentLength();//获取文件的总大小
progressBar.setMax(totalSize);//设置总进度
int len = 0;
Long startTime = System.currentTimeMillis();//开始时间
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
progressBar.setProgress((int) file.length());//设置完成进度
Long stopTime = System.currentTimeMillis();//结束时间
Long time = (stopTime - startTime) / 1000;//读取用时时间
if (time != 0) {
//下载百分比
int percent = (int) (file.length() * 100 / totalSize);
//下载速度
int speed = (int) (file.length() / 1024 / time);
//下载时间
int useTime = (int) (stopTime - startTime) / 1000;
Message msg = new Message();
msg.obj = speed;
msg.arg1 = percent;
msg.arg2 = useTime;
handler.sendMessage(msg);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}

if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android