APK安装器
APK安装器
查看系统源码:E:\android4.2源码aosp_jb422\packages\apps\PackageInstaller
<requestFocus/> 如果是真机,表示弹出一个软键盘
// 注意:以下两个方法,互相冲突,谁在前面,后面的就会把前面的数据给清空
//intent.setData(Uri.fromFile(new File(path)));//This method automatically clears any type that was previously set by setType or setTypeAndNormalize.
//intent.setType("application/vnd.android.package-archive");//This method automatically clears any data that was previously set (for example by setData).
综合方案:
intent.setDataAndType(Uri.
fromFile
(
new
File(path)),
"application/vnd.android.package-archive"
);
|
1、布局: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_path"
android:hint="请输入apk文件的路径"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="/mnt/sdcard/camera.apk"
>
<requestFocus />
</EditText>
<Button
android:onClick="install"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="安装应用" />
</LinearLayout> |
2、代码: package cn.zengfansheng.apkInstaller;
import java.io.File;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText et_path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) this.findViewById(R.id.et_path);
}
/**
* TODO 点击安装应用
* @param view
*/
@SuppressLint("InlinedApi")
public void install(View view){
// <intent-filter>
// <action android:name="android.intent.action.VIEW" />
// <action android:name="android.intent.action.INSTALL_PACKAGE" />
// <category android:name="android.intent.category.DEFAULT" />
// <data android:scheme="file" />
// <data android:mimeType="application/vnd.android.package-archive" />
// </intent-filter>
String path = et_path.getText().toString(); // 直接调用系统的PackageInstaller
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSTALL_PACKAGE);// "android.intent.action.INSTALL_PACKAGE"
intent.addCategory(Intent.CATEGORY_DEFAULT); // 注意:以下两个方法,互相冲突,谁在前面,后面的就会把前面的数据给清空
//intent.setData(Uri.fromFile(new File(path)));//This method automatically clears any type that was previously set by setType or setTypeAndNormalize.
//intent.setType("application/vnd.android.package-archive");//This method automatically clears any data that was previously set (for example by setData).
intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
startActivity(intent);
}
} |