从一个activity跳转到另一个程序的指定activity(含apk检测)

时间:2021-09-28 23:49:33

package com.anqiansong.themedemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {
	private File APK_DIR = new File(Environment.getExternalStorageDirectory().toString()+"/APK");
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.click).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					PackageInfo packageInfo=getPackageManager().getPackageInfo("com.anqiansong.customview", 0);
					ComponentName comp = new ComponentName("com.anqiansong.customview","com.anqiansong.customview.MainActivity");
					Intent intent=new Intent();
					intent.setComponent(comp);
					intent.setAction("android.intent.action.VIEW");
					startActivity(intent);
				} catch (NameNotFoundException e) {
					//没有安装该程序
					Intent intent = new Intent(Intent.ACTION_VIEW); 
					File apk=copyApkFromAssets("CustomView.apk");
					intent.setDataAndType(Uri.fromFile(apk),  
							"application/vnd.android.package-archive");  
					MainActivity.this.startActivity(intent);  
				}
			}
		});

	}
	private File copyApkFromAssets(String apkName){
		File f = null;
		try {
			if(!APK_DIR.exists()){
				APK_DIR.mkdirs();
			}
			InputStream is = getAssets().open(apkName);
			f = new File(APK_DIR, apkName);
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len=is.read(buffer))!=-1){
				fos.write(buffer, 0, len);
			}
			fos.flush();
			fos.close();
			is.close();
			return f;
		} catch (Exception e) {
			//报错不执行
		}
		return null;
	}

}

源码下载: 点击下载

从一个activity跳转到另一个程序的指定activity(含apk检测)


觉得有用支持一下,谢谢!