Android apk的安裝、卸載、更新升級(經過Eclipse實現靜默安裝)

1、經過Intent消息機制發送消息,調用系統應用進行,實現apk的安裝/卸載    
(1)  調用系統的安裝應用,讓系統自動進行apk的安裝  
String fileName = "/data/data/com.zlc.ipanel.operate/FileOperate.apk";
		Uri uri = Uri.fromFile(new File(fileName));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
    上訴安裝不只能夠安裝新的apk(從無到有),也能夠用於更新舊的apk(版本更新),在進行版本更新的時候,必須保證兩個apk的簽名是一致的。 
    若是是通常應用,安裝到data/分區下面,新的apk會替換舊的apk。 
    若是是系統應用,通常安裝到system/app下面,更新以後,  system/app/下的舊apk仍然存在,系統會將新的apk被複制到data/app下。雖然同時存在兩新舊apk,但運行時系統選擇data分區的新apk運行,   若是執行卸載則是刪除data分區的apk,再次啓動程序運行的是system目錄下舊的apk。  
(2)啓動系統的卸載應用,讓系統自動卸載apk 
//經過程序的包名建立URI 
Uri packageURI = Uri.parse("package:com.zlc.ipanel"); 
//建立Intent意圖 
Intent intent = new Intent(Intent.ACTION_DELETE,packageURI); 
//執行卸載程序 
startActivity(intent);

與apk安裝不一樣的是,Intent消息這裏改了:ACTION_DELETE,apk安裝使用的是(ACTION_VIEW) java

2、經過調用系統提供的接口packageManager對apk進行卸載、安裝、獲取權限等(靜默安裝)
(1)須要平臺簽名(寫個Android.mk在源碼下編譯最省事,固然網上也有不少其餘方法,好比:singapk命令行簽名
(2)因爲調用的是未公開的API,因此須要引入源碼(僅僅作一個馬甲,不參與編譯)
(3)在AndroidManifest.xml添加安裝apk的權限
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
(4)若是升級失敗出現 Unable to open zip '/data/FileOperate.apk': Permission denied,說明是權限不夠,有可能當前apk只有(-rw-------)權限,經過Runtime.exec方法修改權限以後再進行升級是能夠成功的。
android

PackageManager pm = this.getPackageManager();
		File file = new File("/data/data/com.zlc.ipanel.operate/FileOperate.apk");
		pm.installPackage(Uri.fromFile(file), null,
				PackageManager.INSTALL_REPLACE_EXISTING, "com.zlc.ipanel");

(5)下面舉一個例子經過Eclipse來實現靜默安裝/卸載
    1)按照咱們上面講的靜默安裝需求一步步實現咱們的操做。首先準備馬甲(靜默安裝須要調用的接口)
    因爲調用了系統未公開的接口,而這些接口有些是經過aidl實現的,下面咱們把須要的馬甲修改一下。
    PackageManager.java shell

/*
 * Copyright (C) 2006 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 android.content.pm;

import android.content.Context;
import android.net.Uri;

/**
 * Class for retrieving various kinds of information related to the application
 * packages that are currently installed on the device.
 *
 * You can find this class through {@link Context#getPackageManager}.
 */
public abstract class PackageManager {

    /**
     * Flag parameter for {@link #installPackage} to indicate that you want to replace an already
     * installed package, if one exists.
     * @hide
     */
    public static final int INSTALL_REPLACE_EXISTING = 0x00000002;


    /**
     * @hide
     *
     * Install a package. Since this may take a little while, the result will
     * be posted back to the given observer.  An installation will fail if the calling context
     * lacks the {@link android.Manifest.permission#INSTALL_PACKAGES} permission, if the
     * package named in the package file's manifest is already installed, or if there's no space
     * available on the device.
     *
     * @param packageURI The location of the package file to install.  This can be a 'file:' or a
     * 'content:' URI.
     * @param observer An observer callback to get notified when the package installation is
     * complete. {@link IPackageInstallObserver#packageInstalled(String, int)} will be
     * called when that happens.  observer may be null to indicate that no callback is desired.
     * @param flags - possible values: {@link #INSTALL_FORWARD_LOCK},
     * {@link #INSTALL_REPLACE_EXISTING}, {@link #INSTALL_ALLOW_TEST}.
     * @param installerPackageName Optional package name of the application that is performing the
     * installation. This identifies which market the package came from.
     */
    public abstract void installPackage(
            Uri packageURI, IPackageInstallObserver observer, int flags,
            String installerPackageName);


    /**
     * Attempts to delete a package.  Since this may take a little while, the result will
     * be posted back to the given observer.  A deletion will fail if the calling context
     * lacks the {@link android.Manifest.permission#DELETE_PACKAGES} permission, if the
     * named package cannot be found, or if the named package is a "system package".
     * (TODO: include pointer to documentation on "system packages")
     *
     * @param packageName The name of the package to delete
     * @param observer An observer callback to get notified when the package deletion is
     * complete. {@link android.content.pm.IPackageDeleteObserver#packageDeleted(boolean)} will be
     * called when that happens.  observer may be null to indicate that no callback is desired.
     * @param flags - possible values: {@link #DONT_DELETE_DATA}
     *
     * @hide
     */
    public abstract void deletePackage(
            String packageName, IPackageDeleteObserver observer, int flags);

  
}

安裝成功的回調接口IPackageInstallObserver.java(修改過的馬甲)
express

package android.content.pm;

import android.os.RemoteException;

public interface IPackageInstallObserver {
	public class Stub implements IPackageInstallObserver{
		public void packageInstalled(String packageName, int returnCode)
				throws RemoteException {
			// TODO Auto-generated method stub
			
		}
	}
}
卸載成功的回調接口IPackageDeleteObserver.java(修改過的馬甲)
package android.content.pm;

public interface IPackageDeleteObserver {
	public class Stub implements IPackageDeleteObserver{
		public void packageDeleted(String packageName, int returnCode) {
			// TODO Auto-generated method stub		
		}
	}	
}
    2)馬甲準備好以後,就開始實現咱們的操做邏輯。
    實現靜默安裝/卸載的方法,而且註冊回調(不管失敗成功都會返回對應值)   
//靜默安裝
	public static void installApkDefaul(Context context,String fileName,String pakcageName){
		Log.d(TAG, "jing mo an zhuang");
		File file = new File(fileName);
		int installFlags = 0;
		if(!file.exists())
			return;
		Log.d(TAG, "jing mo an zhuang  out");
		installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;  
		PackageManager pm = context.getPackageManager();
		IPackageInstallObserver observer = new MyPakcageInstallObserver(); 
		pm.installPackage(Uri.fromFile(file), observer, installFlags, pakcageName);
	}
	//靜默卸載
	public static void uninstallApkDefaul(Context context,String packageName){
		PackageManager pm = context.getPackageManager();
		IPackageDeleteObserver observer = new MyPackageDeleteObserver();
        pm.deletePackage(packageName, observer, 0);
	}
	//靜默卸載回調
	private static class MyPackageDeleteObserver extends IPackageDeleteObserver.Stub{
		@Override
		public void packageDeleted(String packageName, int returnCode) {
			// TODO Auto-generated method stub
			Log.d(TAG, "returnCode = "+returnCode);//返回1表明卸載成功
		}

	}
	//靜默安裝回調
	private static class MyPakcageInstallObserver extends IPackageInstallObserver.Stub{
		@Override
		public void packageInstalled(String packageName, int returnCode)
				throws RemoteException {
			// TODO Auto-generated method stub
		     Log.i(TAG, "returnCode = " + returnCode);//返回1表明安裝成功  
		}
	}
    3)主要的邏輯實現以後,在AndroidManifest.xml 添加安裝和卸載的權限
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
    4)運行Eclipse,生成該應用的apk,下面就要進行系統簽名了。寫一個腳原本來實現替換成系統簽名
    使用簽名包簽名首先咱們要去源碼裏面取出下面這幾個文件platform.x509.pem、platform.pk八、signapk.jar
    
     腳本1.bat 和生成的apk以及上面三個文件放到同一個目錄下面,通常爲工程下面的bin目錄)
java -jar  signapk.jar  platform.x509.pem  platform.pk8 FileUpdateControl.apk 1.apk
adb uninstall com.zlc.ipanel.operate
adb  install 1.apk
    5)當下載到系統裏面的apk權限不夠時(靜默安裝提示權限問題, 有可能當前apk只有(-rw-------)權限
    可使用下面三種方式修改權限

    1.使用Runtime來啓動一個線程修改權限 apache

try {
			Runtime.getRuntime().exec("chmod 777 " + file.getCanonicalPath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    2.寫一個native接口直接經過jni調用c的接口修改權限。
    3.使用FileUtils,這個類默認是隱藏的,官方sdk中不包含這個類,因此代碼若是要使用這個類,須要將工程放到android源碼中編譯
          FileUtils.setPermissions(f.getAbsolutePath(), FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP | FileUtils.S_IROTH, -1, -1) ; app

3、其餘apk安裝的方法 less

    (1)經過cmd窗口 adb 命令,install / uninstall apk。
    (2)cp apk 到 system/app目錄下,系統會自動安裝 
    (3)直接經過代碼調用pm命令執行apk的安裝和卸載 
    1 execCommand("pm", "install", "-f", filePath);//安裝apk,filePath爲apk文件路徑,如/sdcard/operate.apk

    2 execCommand("pm", "uninstall", packageName);//卸載apk,packageName爲包名,如com.zlc.ipanel

靜默安裝依賴源碼包下載
相關文章
相關標籤/搜索