狂刷Android范例之4:用代码安装卸载app
说明
狂刷Android范例系列文章开张了。每篇学习一个Android范例,将一个范例单独生成一个可运行的app,并对重点源代码进行简要分析。然后提供打包好的源代码下载。
功能
这个范例用来展示如何在程序中使用Intent来安装和卸载一个apk文件到用户的手机上。
其主要使用了Intent的Action和Data属性来指明希望的操作和需要安装的apk文件路径,该apk是放在本app的asset目录中作为一个资源。
代码包在此,无需下载分:
http://download.csdn.net/detail/logicteamleader/8797651
来源
ReadAsset例子来自于Android-20的com.example.android.apis.content.InstallApk。
我进行了一点修改,主要是用上篇blog中产生的ClipboardSample.apk文件替换了原来的HelloActivity.apk,因为HelloActivity.apk在我的手机上因为版本问题不能安装。因此采用了与本程序相同版本的ClipboardSample.apk,确保本程序能够正常运行。
环境
代码运行环境:
1.ADT2014版本;
2.android:minSdkVersion=”14”;android:targetSdkVersion=”20”
3.workspace中已经生成了appcompatv7,它的版本是android-22;
代码
需要注意的类就是Intent,它的隐式调用方法。
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.installapk;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* Demonstrates using the INSTALL_PACKAGE Intent to install an application
*/
public class InstallApk extends Activity {
static final int REQUEST_INSTALL = 1;
static final int REQUEST_UNINSTALL = 2;
static final String MY_APK_NAME ="ClipboardSample.apk";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install_apk);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.unknown_source);
button.setOnClickListener(mUnknownSourceListener);
button = (Button)findViewById(R.id.my_source);
button.setOnClickListener(mMySourceListener);
button = (Button)findViewById(R.id.replace);
button.setOnClickListener(mReplaceListener);
button = (Button)findViewById(R.id.uninstall);
button.setOnClickListener(mUninstallListener);
button = (Button)findViewById(R.id.uninstall_result);
button.setOnClickListener(mUninstallResultListener);
}
/*
* 启动的Activity返回时的处理函数,主要是根据requestCode和resultCode进行install和uninstall成功
* 或者失败的信息展示
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_INSTALL) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Install succeeded!", Toast.LENGTH_SHORT).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Install canceled!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Install Failed!", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_UNINSTALL) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Uninstall succeeded!", Toast.LENGTH_SHORT).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Uninstall canceled!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Uninstall Failed!", Toast.LENGTH_SHORT).show();
}
}
}
//通过设置Intent的Action为Intent.ACTION_INSTALL_PACKAGE
//来启动一个系统app进行apk文件的安装
//apk文件的uri在intent的data中设置
private OnClickListener mUnknownSourceListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(prepareApk(MY_APK_NAME)));
startActivity(intent);
}
};
// 同上,区别是设置了一些参数,并且使用startActivityForResult启动intent,可得到返回结果
private OnClickListener mMySourceListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(prepareApk(MY_APK_NAME)));
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
getApplicationInfo().packageName);
startActivityForResult(intent, REQUEST_INSTALL);
}
};
//使用intent来替换一个apk,可得到返回结果
private OnClickListener mReplaceListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(prepareApk(MY_APK_NAME)));
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
getApplicationInfo().packageName);
startActivityForResult(intent, REQUEST_INSTALL);
}
};
//使用intent来卸载一个app
private OnClickListener mUninstallListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse(
"package:com.example.clipboardsample"));
startActivity(intent);
}
};
//使用intent来卸载一个app,可得到返回结果
private OnClickListener mUninstallResultListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse(
"package:com.example.clipboardsample"));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, REQUEST_UNINSTALL);
}
};
private File prepareApk(String assetName) {
// Copy the given asset out into a file so that it can be installed.
// Returns the path to the file.
byte[] buffer = new byte[8192];
InputStream is = null;
FileOutputStream fout = null;
try {
is = getAssets().open(assetName);
fout = openFileOutput("tmp.apk", Context.MODE_WORLD_READABLE);
int n;
while ((n=is.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i("InstallApk", "Failed transferring", e);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
}
try {
if (fout != null) {
fout.close();
}
} catch (IOException e) {
}
}
return getFileStreamPath("tmp.apk");
}
}