android中 捆綁多個apk文件

有時一個大項目下面會有很多個小模塊,如果小模塊之間沒有聯繫,這時可以將每個小模塊作爲單獨的項目,生成apk。

這時就涉及到怎麼將多個apk放到一個項目中。

首先,將小模塊生成的apk放到項目的assets文件夾中


package cn.onecomm.zhenghe.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private ImageView baoxian_zhushou;
	ArrayList<String> packagNameList;
	private MyReceiver receiver;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		initpackagNameList();

		// 監聽系統新安裝程序的廣播
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);// 註冊廣播機制
		filter.addDataScheme("package"); // 必須添加這項,否則攔截不到廣播
		registerReceiver(receiver, filter);

		baoxian_zhushou = (ImageView) findViewById(R.id.baoxian_zhushou);
               
                 // 主頁面小模塊的圖標
		baoxian_zhushou.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				// 檢查是否已經安裝
				Log.d("time", "clicked start " + System.currentTimeMillis()
						+ "");
				boolean installed = detectApk("cn.oncomm.activity");

				if (installed) {// 已經安裝直接起動
					Log.d("time", "getPackageManager start "
							+ System.currentTimeMillis() + "");

					Intent intent = new Intent();
					// 組件名稱,第一個參數是包名,也是主配置文件Manifest裏設置好的包名 第二個是類名,要帶上包名
					intent.setComponent(new ComponentName("cn.oncomm.activity",
							"cn.oncomm.activity.MailActivity"));
					intent.setAction(Intent.ACTION_VIEW);

					Log.d("time", "setAction start "
							+ System.currentTimeMillis() + "");
					startActivity(intent);

				} else {// 未安裝先安裝
					//
					// get the cacheDir.
					File fileDir = getFilesDir();
					final String cachePath = fileDir.getAbsolutePath()
							+ "/pingAnAccident3.0.apk";
					retrieveApkFromAssets(MainActivity.this,
							"pingAnAccident3.0.apk", cachePath);
					showInstallConfirmDialog(MainActivity.this, cachePath);
				}
			}
		});
	}

	// 捆綁安裝
	public boolean retrieveApkFromAssets(Context context, String fileName,
			String path) {
		boolean bRet = false;

		try {
			File file = new File(path);
			if (file.exists()) {
				return true;
			} else {
				file.createNewFile();
				InputStream is = context.getAssets().open(fileName);
				FileOutputStream fos = new FileOutputStream(file);

				byte[] temp = new byte[1024];
				int i = 0;
				while ((i = is.read(temp)) != -1) {
					fos.write(temp, 0, i);
				}
				fos.flush();
				fos.close();
				is.close();

				bRet = true;
			}

		} catch (IOException e) {
			Toast.makeText(context, e.getMessage(), 2000).show();
			Builder builder = new Builder(context);
			builder.setMessage(e.getMessage());
			builder.show();
			e.printStackTrace();
		}

		return bRet;
	}

	/**
	 *提示用戶安裝程序
	 */
	public void showInstallConfirmDialog(final Context context,
			final String filePath) {
		AlertDialog.Builder tDialog = new AlertDialog.Builder(context);
		tDialog.setIcon(R.drawable.info);
		tDialog.setTitle("未安裝該程序");
		tDialog.setMessage("請安裝該程序");

		tDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {

				// 修改apk權限
				try {
					String command = "chmod " + "777" + " " + filePath;
					Runtime runtime = Runtime.getRuntime();
					runtime.exec(command);
				} catch (IOException e) {
					e.printStackTrace();
				}
				// install the apk.
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.parse("file://" + filePath),
						"application/vnd.android.package-archive");
				context.startActivity(intent);

			}
		});

		tDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
			}
		});

		tDialog.show();
	}

	/**
	 * 檢測是否已經安裝
	 * 
	 * @param packageName
	 * @return true已安裝 false未安裝
	 */
	private boolean detectApk(String packageName) {
		return packagNameList.contains(packageName.toLowerCase());

	}

	private void initpackagNameList() {
		// 初始化小模塊列表
		packagNameList = new ArrayList<String>();
		PackageManager manager = this.getPackageManager();
		List<PackageInfo> pkgList = manager.getInstalledPackages(0);
		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = pkgList.get(i);
			packagNameList.add(pI.packageName.toLowerCase());
		}

	}

	/**
	 * 
	 * 設置廣播監聽
	 * 
	 */
	private class MyReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {

				String packName = intent.getDataString().substring(8);

				Log.e(intent.getDataString() + "====", packName);
				// package:cn.oncomm.activity cn.oncomm.activity
				// packName爲所安裝的程序的包名
				packagNameList.add(packName.toLowerCase());

				// 刪除file目錄下的所有以安裝的apk文件
				File file = getFilesDir();
				File[] files = file.listFiles();
				for (File f : files) {
					if (f.getName().endsWith(".apk")) {
						f.delete();
					}
				}

			}
		}
	}
}
主界面:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/layContain" android:layout_width="fill_parent"
	android:layout_height="fill_parent" android:orientation="horizontal">
	<!-- android:background="#FFC0CB"-->


	<LinearLayout android:id="@+id/layFirst"
		android:layout_width="400px" android:layout_height="fill_parent"
		android:orientation="vertical" android:layout_marginBottom="50dp">

		<LinearLayout android:layout_width="fill_parent"
			android:layout_height="fill_parent" android:orientation="vertical">

			<LinearLayout android:layout_width="fill_parent"
				android:layout_height="wrap_content" android:orientation="horizontal"
				android:layout_marginTop="30dp">
 
				<LinearLayout android:layout_width="wrap_content"
					android:layout_height="wrap_content" android:layout_weight="1"
					android:gravity="center_horizontal" android:orientation="vertical">

					<ImageView android:id="@+id/baoxian_zhushou"
						android:layout_width="wrap_content" android:layout_height="wrap_content"
						android:src="@drawable/icon" />
					<TextView android:layout_width="wrap_content"
						android:layout_height="wrap_content" android:text="平安助手"
						  />

				</LinearLayout>
				
								
			</LinearLayout>
		</LinearLayout>
	</LinearLayout>
</LinearLayout>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章