import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.IPackageInstallObserver; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class InstallActivity extends Activity { /** Called when the activity is first created. */ private Button btn=null; private Button btn2=null; private final int INSTALL_COMPLETE = 1; final static int SUCCEEDED = 1; final static int FAILED = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn=(Button) findViewById(R.id.btn1); btn2=(Button) findViewById(R.id.btn2); btn2.setOnClickListener(listener2); } private OnClickListener listener2=new OnClickListener(){ public void onClick(View v) { String fileName = Environment.getExternalStorageDirectory() + "/360buy.apk"; Uri uri = Uri.fromFile(new File(fileName)); int installFlags = 0; PackageManager pm = getPackageManager(); try { PackageInfo pi = pm.getPackageInfo("com.uc.browser", PackageManager.GET_UNINSTALLED_PACKAGES); if(pi != null) { installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; } } catch (NameNotFoundException e) { } // String installerPackageName = getIntent().getStringExtra( // Intent.EXTRA_INSTALLER_PACKAGE_NAME); PackageInstallObserver observer = new PackageInstallObserver(); pm.installPackage(uri, observer, installFlags, "com.uc.browser"); } }; class PackageInstallObserver extends IPackageInstallObserver.Stub { public void packageInstalled(String packageName, int returnCode) { Message msg = mHandler.obtainMessage(INSTALL_COMPLETE); msg.arg1 = returnCode; mHandler.sendMessage(msg); } }; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case INSTALL_COMPLETE: // Update the status text // Show the ok button int centerTextLabel; Drawable centerTextDrawable = null; if(msg.arg1 == SUCCEEDED) { } else {} if (centerTextDrawable != null) {} break; default: break; } } }; }<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
http://www.2cto.com/kf/201204/128607.html html
重點是要實現一個這個類PackageInstallObserver,另外要注意import android.content.pm.……的那些包必定要導入。android.mk文件以下 java
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := user
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_PACKAGE_NAME := InstallActivity
LOCAL_CERTIFICATE := platform
include $(BUILD_PACKAGE) android
重點是LOCAL_CERTIFICATE := platform要對 app