远程下载安装apk文件到手机或模拟器

废话少说,直接上代码,会加上详细注释:
测试地址:http://www.dubblogs.cc:8751/Android/Test/Apk/EX04_14.apk
Java代码

package cn.com;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/*必须引用java.io与java.net*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public class InstallUrlApk extends Activity
{
private TextView mTextView01;
private EditText mEditText01;

//点击下载的按钮

private Button mButton01;
private static final String TAG = "DOWNLOADAPK";
private String currentFilePath = "";
private String currentTempFilePath = "";
private String strURL = "";
private String fileEx = "";
private String fileNa = "";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTextView01 = (TextView) findViewById(R.id.myTextView1);
mButton01 = (Button) findViewById(R.id.myButton1);
mEditText01 = (EditText) findViewById(R.id.myEditText1);

mButton01.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
/* 文件会下载至local端 */
mTextView01.setText("下载中...");
strURL = mEditText01.getText().toString();
/取得欲安装程序之文件名称(后缀名)
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())
.toLowerCase();

System.out.println("***************fileEx =" + fileEx);

fileNa = strURL.substring(strURL.lastIndexOf("/") + 1, strURL
.lastIndexOf("."));

System.out.println("***************fileNa =" + fileNa);

//开启一个子线程进行文件的下载
getFile(strURL);
}
});

mEditText01.setOnClickListener(new EditText.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
mEditText01.setText("");
mTextView01.setText("远程安装程序(请输入URL)");
}
});
}

/* 处理下载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);
}
}
};
new Thread(r).start();
} catch (Exception e)
{
e.printStackTrace();
}
}

/* 取得远程文件 */
private void getDataSource(String strPath) throws Exception
{
//如果是一个正确的网址,就返回true
if (!URLUtil.isNetworkUrl(strPath))
{
mTextView01.setText("错误的URL");
} else
{
/* 取得URL */
URL myURL = new URL(strPath);
/* 创建连接 */
URLConnection conn = myURL.openConnection();
conn.connect();
/* InputStream 下载文件 */
InputStream is = conn.getInputStream();
if (is == null)
{
throw new RuntimeException("stream is null");
}
// 创建临时文件
// 两个参数分别为前缀和后缀
File myTempFile = File.createTempFile(fileNa, "." + fileEx);

/* 取得站存盘案路径 */
currentTempFilePath = myTempFile.getAbsolutePath();
/* 将文件写入暂存盘 */
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do
{
int numread = is.read(buf);
if (numread <= 0)
{
break;
}
fos.write(buf, 0, numread);
} while (true);

// 打开文件进行安装(下载完成后执行的操作)
openFile(myTempFile);
try
{
is.close();
} catch (Exception ex)
{
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}

// 在手机上打开文件的method
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 = getMIMEType(f);
/* 设置intent的file与MimeType */
intent.setDataAndType(Uri.fromFile(f), type);
startActivity(intent);
}

/* 判断文件MimeType的method */
private String getMIMEType(File f)
{
String type = "";
String fName = f.getName();
/* 取得扩展名 */
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length())
.toLowerCase();

/* 依扩展名的类型决定MimeType */
if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
|| end.equals("xmf") || end.equals("ogg") || end.equals("wav"))
{
type = "audio";
} else if (end.equals("3gp") || end.equals("mp4"))
{
type = "video";
} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
|| end.equals("jpeg") || end.equals("bmp"))
{
type = "image";
} else if (end.equals("apk"))
{
/* android.permission.INSTALL_PACKAGES */
type = "application/vnd.android.package-archive";
} else
{
type = "*";
}
/* 如果无法直接打开,就跳出软件列表给用户选择 */
if (end.equals("apk"))
{
} else
{
type += "/*";
}
return type;
}

/* 自定义删除文件方法 */
private void delFile(String strFileName)
{
File myFile = new File(strFileName);
if (myFile.exists())
{
myFile.delete();
}
}

/* 当Activity处于onPause状态时,更改TextView文字状态 */
@Override
protected void onPause()
{
mTextView01 = (TextView) findViewById(R.id.myTextView1);
mTextView01.setText("下载成功");
super.onPause();
}

/* 当Activity处于onResume状态时,删除临时文件 */
@Override
protected void onResume()
{
// TODO Auto-generated method stub
/* 删除临时文件 */
delFile(currentTempFilePath);
super.onResume();
}
}


package cn.com;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/*必须引用java.io与java.net*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public class InstallUrlApk extends Activity
{
private TextView mTextView01;
private EditText mEditText01;

//点击下载的按钮

private Button mButton01;
private static final String TAG = "DOWNLOADAPK";
private String currentFilePath = "";
private String currentTempFilePath = "";
private String strURL = "";
private String fileEx = "";
private String fileNa = "";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTextView01 = (TextView) findViewById(R.id.myTextView1);
mButton01 = (Button) findViewById(R.id.myButton1);
mEditText01 = (EditText) findViewById(R.id.myEditText1);

mButton01.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
/* 文件会下载至local端 */
mTextView01.setText("下载中...");
strURL = mEditText01.getText().toString();
/取得欲安装程序之文件名称(后缀名)
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())
.toLowerCase();

System.out.println("***************fileEx =" + fileEx);

fileNa = strURL.substring(strURL.lastIndexOf("/") + 1, strURL
.lastIndexOf("."));

System.out.println("***************fileNa =" + fileNa);

//开启一个子线程进行文件的下载
getFile(strURL);
}
});

mEditText01.setOnClickListener(new EditText.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
mEditText01.setText("");
mTextView01.setText("远程安装程序(请输入URL)");
}
});
}

/* 处理下载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);
}
}
};
new Thread(r).start();
} catch (Exception e)
{
e.printStackTrace();
}
}

/* 取得远程文件 */
private void getDataSource(String strPath) throws Exception
{
//如果是一个正确的网址,就返回true
if (!URLUtil.isNetworkUrl(strPath))
{
mTextView01.setText("错误的URL");
} else
{
/* 取得URL */
URL myURL = new URL(strPath);
/* 创建连接 */
URLConnection conn = myURL.openConnection();
conn.connect();
/* InputStream 下载文件 */
InputStream is = conn.getInputStream();
if (is == null)
{
throw new RuntimeException("stream is null");
}
// 创建临时文件
// 两个参数分别为前缀和后缀
File myTempFile = File.createTempFile(fileNa, "." + fileEx);

/* 取得站存盘案路径 */
currentTempFilePath = myTempFile.getAbsolutePath();
/* 将文件写入暂存盘 */
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do
{
int numread = is.read(buf);
if (numread <= 0)
{
break;
}
fos.write(buf, 0, numread);
} while (true);

// 打开文件进行安装(下载完成后执行的操作)
openFile(myTempFile);
try
{
is.close();
} catch (Exception ex)
{
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}

// 在手机上打开文件的method
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 = getMIMEType(f);
/* 设置intent的file与MimeType */
intent.setDataAndType(Uri.fromFile(f), type);
startActivity(intent);
}

/* 判断文件MimeType的method */
private String getMIMEType(File f)
{
String type = "";
String fName = f.getName();
/* 取得扩展名 */
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length())
.toLowerCase();

/* 依扩展名的类型决定MimeType */
if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
|| end.equals("xmf") || end.equals("ogg") || end.equals("wav"))
{
type = "audio";
} else if (end.equals("3gp") || end.equals("mp4"))
{
type = "video";
} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
|| end.equals("jpeg") || end.equals("bmp"))
{
type = "image";
} else if (end.equals("apk"))
{
/* android.permission.INSTALL_PACKAGES */
type = "application/vnd.android.package-archive";
} else
{
type = "*";
}
/* 如果无法直接打开,就跳出软件列表给用户选择 */
if (end.equals("apk"))
{
} else
{
type += "/*";
}
return type;
}

/* 自定义删除文件方法 */
private void delFile(String strFileName)
{
File myFile = new File(strFileName);
if (myFile.exists())
{
myFile.delete();
}
}

/* 当Activity处于onPause状态时,更改TextView文字状态 */
@Override
protected void onPause()
{
mTextView01 = (TextView) findViewById(R.id.myTextView1);
mTextView01.setText("下载成功");
super.onPause();
}

/* 当Activity处于onResume状态时,删除临时文件 */
@Override
protected void onResume()
{
// TODO Auto-generated method stub
/* 删除临时文件 */
delFile(currentTempFilePath);
super.onResume();
}
}
另外例子中还可以通过
Java代码
System.out.println("conn.getContentLength() =" + conn.getContentLength());

System.out.println("conn.getContentLength() =" + conn.getContentLength());获取下载文件的大小,然后来实现PrgressBar的下载进度显示
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值