您的位置:首页 > 移动开发 > Android开发

Android如何实现文件下载并自动安装apk包!!!

2014-03-04 15:37 766 查看

Android程序使用代码的安装和卸载!!!

public class MainActivity extends Activity {

private String currentFilePath = "", currentTempFilePath = "", strURL = "",
fileEx = "", fileNa = "";
File file2 = new File(Environment.getExternalStorageDirectory()+"");
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentLayout = (View) findViewById(R.id.fragment);
gotoButton = (Button) findViewById(R.id.goto_button);
gotoButton.setOnClickListener(gotoListener);
}

OnClickListener gotoListener = new OnClickListener() {

@Override
public void onClick(View v) {

// String webUrl = "http://fancy.189.cn/portal/getclientapk";
// Uri uri = Uri.parse(webUrl);
// Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// startActivity(intent);
// finish();
strURL = "http://fancy.189.cn/portal/getclientapk";
/* 取得欲安装程序名称 */
fileEx = "telecom_mdesk";
fileNa = ".apk";
getFile(strURL);
}
};

/* 处理下载URL文件自定义函数 */
private void getFile(final String strPath) {
try {
if (strPath.equals(currentFilePath)) {
getDataSource(strPath);
}
currentFilePath = strPath;
Runnable r = new Runnable() {
public void run() {
try {
getDataSource(strPath);
} catch (Exception e) {
Log.e("TAG", e.getMessage(), e);
Log.e("TAG", "------>");
}
}
};
new Thread(r).start();
} catch (Exception e) {
e.printStackTrace();
}
}

/* 取得远程文件 */
private void getDataSource(String strPath) throws Exception {
// if (!URLUtil.isNetworkUrl(strPath))
// mTextView01.setText("错误的URL");
// else
// {
/* 取得URL */
URL myURL = new URL(strPath);
/* 创建连接 */
//URLConnection conn = myURL.openConnection();
HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
conn.setRequestMethod("POST");
// is = connection.getInputStream();
//conn.connect();
/* InputStream 下载文件 */
InputStream is = conn.getInputStream();
if (is == null)
throw new RuntimeException("stream is null");

/* 创建临时文件 */
File myTempFile = File.createTempFile(fileEx, fileNa, file2);
/* 取得临时文件路径 */
currentTempFilePath = myTempFile.getAbsolutePath();
/* 将文件写入暂存盘 */
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do {
int numread = is.read(buf);
if (numread <= 0)
break;

Log.v("TAG", "下载中---");

fos.write(buf, 0, numread);
} while (true);

/* 打开文件进行安装 */
openFile(myTempFile);
try {
is.close();
} catch (Exception ex) {
Log.e("TAG", "error: " + ex.getMessage(), ex);
}
// }
}

/**
* 在手机上打开文件
*/
private void openFile(File f) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);

/* 调用getMIMEType()来取得MimeType */
String type = "application/vnd.android.package-archive";
/* 设置intent的file与MimeType */
intent.setDataAndType(Uri.fromFile(f), type);
startActivity(intent);
}
}


安装:

String str = "/CanavaCancel.apk";
String fileName = Environment.getExternalStorageDirectory() + str;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);


卸载:

Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);


Environment拥有一些可以获取环境变量的方法
package:com.demo.CanavaCancel 这个形式是 package:程序完整的路径 (包名+程序名)。
下载apk程序代码:

protected File downLoadFile(String httpUrl) {
// TODO Auto-generated method stub
final String fileName = "updata.apk";
File tmpFile = new File("/sdcard/update");
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
final File file = new File("/sdcard/update/" + fileName);

try {
URL url = new URL(httpUrl);
try {
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[256];
conn.connect();
double count = 0;
if (conn.getResponseCode() >= 400) {
Toast.makeText(Main.this, "连接超时", Toast.LENGTH_SHORT)
.show();
} else {
while (count <= 100) {
if (is != null) {
int numRead = is.read(buf);
if (numRead <= 0) {
break;
} else {
fos.write(buf, 0, numRead);
}

} else {
break;
}

}
}

conn.disconnect();
fos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}

return file;
}


打开APK程序代码:

private void openFile(File file) {
// TODO Auto-generated method stub
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: