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

Android之应用程序自动升级 下载后…

2014-12-16 20:37 495 查看
当我们的APP升级到新版本时,一般采用的方法就是程序检测服务器上的版本,如果比当前版本更新,则下载服务器上的版本,然后安装。

首先,安装程序需要特殊权限。打开AndroidMenifest.xml,在</application>后、</manifest>之前加上后面的代码: <uses-permission
android:name=”android.permission.INSTALL_PACKAGES”
/>,这样你的APP就有安装软件权限了。

接下是安装的关键代码,下载完后执行:

Uri uri = Uri.fromFile(new File("/sdcard/temp.apk"));
//这里是APK路径

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(uri,"application/vnd.android.package-archive");

startActivity(intent);

//网络下载apk文件然后安装

public class Main extends Activity implements
OnClickListener

{

private void installApk(String filename)

{

File file = new
File(filename);

Intent intent = new
Intent();

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.setAction(Intent.ACTION_VIEW);

String type =
"application/vnd.android.package-archive";

intent.setDataAndType(Uri.fromFile(file),
type);

startActivity(intent);

}

@Override

public void onClick(View view)

{

String downloadPath =
Environment.getExternalStorageDirectory().getPath() +
"/download_cache";

String url = "http://192.168.1.55/xinlangweibo_1_0.apk";

File file = new
File(downloadPath);

if(!file.exists())

{

file.mkdir();

}

HttpGet httpGet = new
HttpGet(url);

try

{

HttpResponse
httpResponse = new DefaultHttpClient()

.execute(httpGet);

if
(httpResponse.getStatusLine().getStatusCode() == 200)

{

InputStream
is = httpResponse.getEntity().getContent();

FileOutputStream
fos = new FileOutputStream(downloadPath

+
"/integration.apk");

byte[]
buffer = new byte[8192];

int
count = 0;

while
((count = is.read(buffer)) != -1)

{

fos.write(buffer,
0, count);

}

fos.close();

is.close();

installApk(downloadPath+
"/integration.apk");

}

}

catch (Exception e)

{

}

}

@Override

public void onCreate(Bundle
savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button btnDownloadInstallApk =
(Button) findViewById(R.id.btnDownloadInstallApk);

btnDownloadInstallApk.setOnClickListener(this);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: