`

模仿安卓市场自动下载安装打开apk应用程序

 
阅读更多
主程序
package com.example.downloadnotify;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener{

	String downloadUrl = "http://xxx";
	String fileDir = "/sdcard/xxx/";
	String fileName = fileDir+"xxx.apk";
	private static Button btn;  
	private Handler handler = new Handler() {};
	
	@Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        btn = (Button) findViewById(R.id.button1);  
        btn.setOnClickListener(this);  
        File f = new File(fileDir);
        if(!f.exists()){
        	f.mkdirs();
        }
        initBtnState();
	}  
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		File f = new File(fileDir);
        if(!f.exists()){
        	f.mkdirs();
        }
		initBtnState();
	}
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method 
		btnClickAction();
	}
	
	private void initBtnState(){
		if(checkBrowser("com.explusalpha.NesEmu")){
			//start();
			btn.setText("打开");
		}else{
			File file = new File(fileName);
			if(file.exists()){
				btn.setText("安装");
			}else{
				btn.setText("下载");
			}
		}
	}
	
	private void btnClickAction(){
		if(btn.getText().toString().equals("下载")){
			AppFileDownUtils afd = new AppFileDownUtils(this, handler, downloadUrl, fileName);
			String state = afd.getState().toString();
			if(state.equals(Thread.State.NEW.name())){
				afd.start();
			}
		}else if(btn.getText().toString().equals("安装")){
			install();
		}else if(btn.getText().toString().equals("打开")){
			start();
		}
	}
	
	private void start(){
   	 ComponentName componentName=new   ComponentName
   	 ("com.explusalpha.NesEmu","com.imagine.BaseActivity");   
        Intent intent=new Intent();   
        intent.setComponent(componentName);   
        intent.setAction(Intent.ACTION_VIEW);   
        startActivity(intent); 
   }
	
	private void install(){
		Intent intent = new Intent(Intent.ACTION_VIEW);  
        intent.setDataAndType(Uri.parse("file://"  
                +fileName),  
                "application/vnd.android.package-archive");  
        startActivity(intent);
	}
	
	public boolean checkBrowser(String packageName) {  
	    if (packageName == null || "".equals(packageName))  
	        return false;  
	    try {  
	        ApplicationInfo info = getPackageManager().getApplicationInfo(  
	                packageName, PackageManager.GET_UNINSTALLED_PACKAGES);  
	        return true;  
	    } catch (NameNotFoundException e) {  
	        return false;  
	    }  
	}  
	public static Runnable updateInstallBtn = new Runnable() {
		public void run() {
            if (btn != null) {
            	btn.setText("安装");
            }
        }
    };

}



activity_main.xml
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical" >  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="下载" />  
  
</LinearLayout>  


下载线程(注意android3.0以后规定网络操作必须开启另一个线程执行,否则报错android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099))
package com.example.downloadnotify;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class AppFileDownUtils extends Thread {  
  
    private Context mContext;  
    private Handler mHandler;  
    private String mDownloadUrl; // 文件下载url,已做非空检查  
    private String mFileName;  
    private Message msg;  
  
    public static final int MSG_UNDOWN = 0; //未开始下载  
    public static final int MSG_DOWNING = 1; // 下载中  
    public static final int MSG_FINISH = 1; // 下载完成  
    public static final int MSG_FAILURE = 2;// 下载失败  
  
    private NotificationManager mNotifManager;  
    private Notification mDownNotification;  
    private RemoteViews mContentView; // 下载进度View  
    private PendingIntent mDownPendingIntent;  
  
    public AppFileDownUtils(Context context, Handler handler,  
            String downloadUrl, String fileName) {  
        mContext = context;  
        mHandler = handler;  
        mDownloadUrl = downloadUrl;  
        mFileName = fileName;  
        mNotifManager = (NotificationManager) mContext  
                .getSystemService(Context.NOTIFICATION_SERVICE);  
        msg = new Message();  
    }  
  
    @Override  
    public void run() {  
        try {  
            if (Environment.getExternalStorageState().equals(  
                    Environment.MEDIA_MOUNTED)) {  
                Message downingMsg = new Message();  
                downingMsg.what = MSG_DOWNING;  
                mHandler.sendMessage(downingMsg);  
                File saveFilePath = new File(mFileName);  
                System.out.println(saveFilePath);  
                mDownNotification = new Notification(  
                        android.R.drawable.stat_sys_download, "下载中", System  
                                .currentTimeMillis());  
                mDownNotification.flags = Notification.FLAG_ONGOING_EVENT;  
                mDownNotification.flags = Notification.FLAG_AUTO_CANCEL;  
                mContentView = new RemoteViews(mContext.getPackageName(),  
                        R.layout.custom_notification);  
                mContentView.setImageViewResource(R.id.downLoadIcon,  
                        android.R.drawable.stat_sys_download);  
                mDownPendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);  
                boolean downSuc = downloadFile(mDownloadUrl, saveFilePath);  
                if (downSuc) {  
                    msg.what = MSG_FINISH;  
                    Notification notification = new Notification(  
                            android.R.drawable.stat_sys_download_done, "下载成功",  
                            System.currentTimeMillis());  
                    notification.flags = Notification.FLAG_ONGOING_EVENT;  
                    notification.flags = Notification.FLAG_AUTO_CANCEL;  
                    Intent intent = new Intent(Intent.ACTION_VIEW);  
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
                    intent.setDataAndType(Uri.fromFile(saveFilePath),  
                            "application/vnd.android.package-archive");  
                    PendingIntent contentIntent = PendingIntent.getActivity(  
                            mContext, 0, intent, 0);  
                    notification.setLatestEventInfo(mContext, "下载成功", null,  
                            contentIntent);  
                    mNotifManager.notify(R.drawable.ic_launcher, notification); 
                    mHandler.post(Main.updateInstallBtn);
                } else {  
                    msg.what = MSG_FAILURE;  
                    Notification notification = new Notification(  
                            android.R.drawable.stat_sys_download_done, "下载失败",  
                            System.currentTimeMillis());  
                    notification.flags = Notification.FLAG_AUTO_CANCEL;  
                    PendingIntent contentIntent = PendingIntent.getActivity(  
                            mContext, 0, new Intent(), 0);  
                    notification.setLatestEventInfo(mContext, "下载失败", null,  
                            contentIntent);  
                    mNotifManager.notify(R.drawable.ic_launcher, notification);  
                }  
  
            } else {  
                Toast.makeText(mContext, Environment.getExternalStorageState(),  
                        Toast.LENGTH_SHORT).show();  
                msg.what = MSG_FAILURE;  
            }  
        } catch (Exception e) {  
            Log.e("AppfileDownUtils", "AppFileDownUtils catch Exception:", e);  
            msg.what = MSG_FAILURE;  
        } finally {  
            mHandler.sendMessage(msg);  
        }  
    }  
  
    /** 
     *  
     * Desc:文件下载 
     *  
     * @param downloadUrl 
     *            下载URL 
     * @param saveFilePath 
     *            保存文件路径 
     * @return ture:下载成功 false:下载失败 
     */  
    private boolean downloadFile(String downloadUrl, File saveFilePath) {  
        int fileSize = -1;  
        int downFileSize = 0;  
        boolean result = false;  
        int progress = 0;  
        try {  
            URL url = new URL(downloadUrl);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            if (null == conn) {  
                return false;  
            }  
            // 读取超时时间 毫秒级  
            conn.setReadTimeout(10000);  
            conn.setRequestMethod("GET");  
            conn.setDoInput(true);  
            conn.connect();  
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
                fileSize = conn.getContentLength();  
                InputStream is = conn.getInputStream();  
                FileOutputStream fos = new FileOutputStream(saveFilePath);  
                byte[] buffer = new byte[1024];  
                int i = 0;  
                int tempProgress = -1;  
                while ((i = is.read(buffer)) != -1) {  
                    downFileSize = downFileSize + i;  
                    // 下载进度  
                    progress = (int) (downFileSize * 100.0 / fileSize);  
                    fos.write(buffer, 0, i);  
  
                    synchronized (this) {  
                        if (downFileSize == fileSize) {  
                            // 下载完成  
                            mNotifManager.cancel(R.id.downLoadIcon);  
                        } else if (tempProgress != progress) {  
                            // 下载进度发生改变,则发送Message  
                            mContentView.setTextViewText(R.id.progressPercent,  
                                    progress + "%");  
                            mContentView.setProgressBar(R.id.downLoadProgress,  
                                    100, progress, false);  
                            mDownNotification.contentView = mContentView;  
                            mDownNotification.contentIntent = mDownPendingIntent;  
                            mNotifManager.notify(R.id.downLoadIcon,  
                                    mDownNotification);  
                            tempProgress = progress;  
                        }  
                    }  
                }  
                fos.flush();  
                fos.close();  
                is.close();  
                result = true;  
            } else {  
                result = false;  
            }  
        } catch (Exception e) {  
            result = false;  
            Log.e("", "downloadFile catch Exception:", e);  
        }  
        return result;  
    }  
}



custom_notification.xml
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
  android:id="@+id/custom_notification"  
  xmlns:android="http://schemas.android.com/apk/res/android"  
  android:orientation="horizontal"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent">  
    <ImageView  
        android:id="@+id/downLoadIcon"  
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"  
        android:layout_marginLeft="5dip"  
        android:layout_gravity="center_vertical"  
        />  
    <TextView  
        android:layout_height="fill_parent"  
        android:layout_width="wrap_content"  
        android:layout_marginLeft="5dip"  
        android:text="下载进度条"  
        android:gravity="center_vertical"  
        />  
    <ProgressBar  
        android:id="@+id/downLoadProgress"  
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_marginLeft="10dip"     
        android:layout_width="150dip"       
        android:layout_height="wrap_content"    
        android:layout_gravity="center_vertical"
        />  
    <TextView  
        android:id="@+id/progressPercent"  
        android:layout_height="fill_parent"  
        android:layout_width="wrap_content"  
        android:layout_marginLeft="5dip"  
        android:gravity="center_vertical"  
        />  
</LinearLayout>  



AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadnotify"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8" 
        android:targetSdkVersion="15"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity  
		    android:label="@string/app_name"  
		    android:name=".Main" >  
		    <intent-filter >  
		        <action android:name="android.intent.action.MAIN" />  
		        <category android:name="android.intent.category.LAUNCHER" />  
		    </intent-filter>  
		</activity>  
  
	<service android:name=".DownLoadService"/>  
    </application>

	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
</manifest>


效果图







  • 大小: 42.6 KB
  • 大小: 32.7 KB
  • 大小: 32.9 KB
  • 大小: 45.3 KB
  • 大小: 32.6 KB
分享到:
评论

相关推荐

    Android 更新下载apk 安装apk 打开apk

    在Android平台上,更新、下载、安装以及打开APK文件是应用程序生命周期中的常见操作。下面将详细阐述这些过程及其相关的知识点。 一、Android APK文件 APK(Android Package)是Android系统中应用程序的安装包,...

    Android实现下载APK文件并自动执行安装

    在Android平台上,实现从网络下载APK文件并自动执行安装是一个常见的需求,尤其在更新应用或者分发非市场应用时。这个过程涉及到多个步骤,包括网络请求、文件下载、权限处理以及安全检查。下面我们将详细讲解如何...

    Android 下载APK 安装APK 打开APK

    在Android系统中,下载、安装和打开APK文件是用户获取和使用应用程序的基本流程。APK(Android Package)是Android操作系统中的应用软件包文件格式,相当于iOS中的.ipa文件。以下将详细介绍这些过程以及实现这一功能...

    Android应用程序apk安装器程序

    Android应用程序apk安装器程序是一种工具,它允许用户在Android设备上方便快捷地安装APK文件。APK是Android应用的二进制格式,相当于iOS中的ipa文件,是开发者完成应用程序开发后编译打包的产物。当用户从非Google ...

    android应用下载安装apk升级版本实现demo适配Android10

    本示例“android应用下载安装apk升级版本实现demo适配Android10”聚焦于如何在Android 10(API级别29)及更高版本中实现这一过程。以下是关于这一主题的详细知识: 1. **安全下载APK**:在Android 10中,为了保障...

    Android 7.0下载安装APK

    本文将详细讲解如何在Android 7.0设备上下载并安装APK应用,以及在这个版本中与APK安装相关的知识点。 1. **APK 文件**:APK 是 Android 应用程序的安装包,类似于 Windows 上的 .exe 文件。它包含了应用的代码、...

    Android App调用没有安装的apk

    在Android平台上,应用程序通常需要先通过Google Play或其他应用商店安装后才能运行。然而,有一种特殊的技术使得Android App能够调用并使用未安装的APK文件,这种技术被称为“插件化开发”。本项目名为"ApkDemo",...

    Android手机端使用Zipalign优化apk应用程序.pdf

    使用 ADB 法需要安装 Android SDK,并使用 ADB 命令行工具将 zipalign 二进制文件推送到 Android 手机的系统目录下,然后执行 zipalign_apks.sh 脚本文件以优化 APK 应用程序。使用 Root Explorer 需要将 zipalign ...

    Android7.0下载Apk自动安装

    标题"Android7.0下载Apk自动安装"直指这一问题,描述中的"下载自动安装Demo,兼容7.0"表明我们有一个示例项目,这个项目演示了如何在Android 7.0及更高版本中实现APK的自动下载和安装,同时确保与该版本系统的兼容性...

    适配Android高低版本自动更新apk安装

    本文将深入探讨如何解决Android10以下及以上的系统版本中,下载更新的APK自动安装失败的问题,为开发者提供实用的解决方案。 首先,我们需要了解Android在不同版本中对于安装APK权限的改变。自Android6.0(API级别...

    Android 自动安装apk

    在Android平台上,自动安装APK是一项常见的操作,尤其对于开发者来说,这有助于快速测试和部署应用。本示例,"Android 自动安装apk",提供了一个DEMO,它允许用户无需手动操作即可安装APK文件。这个过程涉及到...

    Android 8.0不能自动安装APK问题的解决方法(完美适配)

    未知应用安装权限默认开启,如下图所示 8.0以下手机未知应用安装权限.png Android8.0之后 未知应用安装权限默认关闭,且权限入口隐藏。 如何开启未知应用安装权限的入口,并设置允许安装? 在清单文件中添加...

    APK自动静默安装并自动重新启动

    在Android系统中,APK自动静默安装并自动重新启动是一项技术操作,通常涉及到系统级权限和特定的脚本编写。这项技术常用于批量设备管理、应用自动化测试或企业内部应用部署等场景。以下是关于这个主题的详细知识讲解...

    Android 自动更新 下载文件 APK

    本文将深入探讨如何实现Android应用程序的自动更新机制,特别是在下载APK文件方面。我们将基于名为"DownLoadDemo"的源代码实例进行讨论。 1. **Android权限设置**: 在AndroidManifest.xml文件中,需要添加必要的...

    android 无sdcard 下载安装 apk 多线程 断点 自动安装apk

    在这种情况下,用户仍然需要能够下载并安装APK应用。为了实现这一目标,开发者通常会采用多线程下载技术来提高下载速度,并结合断点续传功能,确保在网络不稳定时能恢复中断的下载过程。最后,自动安装APK的机制可以...

    demo.apk unity自动更新 内部安装Apk

    unity 内部更新Apk 自动安装 支持安卓8.0 以上 demo.apk 测试包

    apk自动安装脚本

    自己写了一个脚本,代替91手机助手之类的安装,记得把adb目录加入到系统环境变量,脚本放在任何地方都行,apk拖到脚本上面自动安装~~~apk名字不能有中文

    安卓手机自动关机-定时启动程序-事件触发启动(APK)

    "安卓手机自动关机-定时启动程序-事件触发启动(APK)"就是这样一个应用程序,它允许用户实现这些自动化任务。这款应用通常需要ROOT权限,意味着它能够访问并控制系统的底层功能,这使得它具有更广泛的控制能力。 ...

Global site tag (gtag.js) - Google Analytics