- 浏览: 179686 次
- 性别:
- 来自: 深圳
-
文章分类
主程序
activity_main.xml
下载线程(注意android3.0以后规定网络操作必须开启另一个线程执行,否则报错android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099))
custom_notification.xml
AndroidManifest.xml
效果图
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>
效果图




发表评论
-
跳转至Google Play,rate,more推广功能
2014-08-19 15:09 1143String appPackageName = getPac ... -
Activity 全透明属性
2014-07-02 15:10 580android:theme="@android:st ... -
android平台运行flash游戏
2014-03-31 19:20 874android平台运行flash游戏 http://blo ... -
遍历指定目录下的图片文件 显示在gridview
2014-03-05 12:49 827gridview布局 <?xml version=& ... -
Android桌面悬浮窗进阶,QQ手机管家小火箭效果实现
2014-01-06 15:11 1052http://blog.csdn.net/guolin_b ... -
android 透明效果
2013-06-28 17:25 926参考http://2960629.blog.51cto ... -
拦截Home键
2013-03-19 12:03 969主要就是重写 onAttachedTo ... -
不同应用间数据共享
2013-03-18 11:16 843Android不同应用之间数据的共享有许多方式,但是我觉得还是 ... -
root情况下静默安装
2012-12-17 11:12 865参考 http://blog.csdn.net/su1216/ ... -
app推广必备功能:分享到,更多应用,创建快捷方式
2012-12-14 13:14 1208public class ShareTool { ... -
获取屏幕上正在显示的activity
2012-12-08 17:19 1051参考文章http://chroya.iteye.com/blo ... -
android异步加载数据
2012-11-07 13:55 1002参考http://blog.csdn.net/sfshine/ ... -
Activity去除标题栏和状态栏
2012-11-06 15:50 1393方法一:直接在xml文件里设置 //全屏(隐藏标题栏和状 ... -
无法清除的Notification,直到点击了才可以消除
2012-11-06 12:35 2230参考文章 http://www.cnblogs.com/new ... -
vpn
2012-10-30 17:17 705参考文章http://blog.csdn.net/whyonl ... -
开机启动Service
2012-10-25 14:58 880程序执行效果为: 开机后跳转到MainActivity并执行定 ... -
Android 定时执行任务
2012-10-25 13:28 1983本程序执行效果为: 隔3秒打印"收到广播" ... -
打开关闭移动数据、wifi、gps
2012-10-13 23:11 1036参考 http://blog.csdn.net/anzhu_1 ... -
联网自动开启Service
2012-10-12 10:13 958参考http://blog.csdn.net/lvron/ar ... -
从assets复制文件到sd卡
2012-09-28 21:34 2932参考文章 批量从assets复制文件到sd卡 http://l ...
相关推荐
"FillData"是这样一个专门针对Android系统的工具,它能够模仿用户的行为,填充手机内存,以帮助开发者和测试人员更好地理解和优化应用程序的内存使用情况。下面将详细讨论这个工具的功能、使用方法以及其在实际工作...
1. **自定义快捷键**:用户可以自由配置悬浮球上的按键功能,例如将一个按钮设置为打开特定的应用程序,或者进行屏幕截图等。 2. **位置可调**:悬浮球的位置可以随意移动,用户可以根据自己的习惯将其放置在屏幕的...
"终端模拟器 v1.0.70 (Android 1.6+)" 是一个专为Android平台设计的应用程序,它使得用户能够在手机或平板电脑上运行Linux命令行界面,从而实现一系列高级操作。 首先,我们来解析一下这个应用的名称。"终端模拟器...
通过灵活运用这些布局组件,开发者可以构建出各种复杂的用户界面,满足不同的应用程序需求。在实际开发中,还可以结合其他布局,如LinearLayout、RelativeLayout等,以及自定义View,来实现更多功能和设计效果。
总之,模仿360二维码扫描功能在Android上实现涉及下载ZXing项目,理解其内部结构,解决兼容性问题,添加必要的权限,以及在你的应用中集成和自定义扫描界面和逻辑。通过这个过程,你可以为你的Android应用添加高效且...
【标题】"仿多看阅读as版.rar"指的是一个基于Android Studio(AS)开发的,模仿多看阅读应用的源代码项目。多看阅读是一款知名的电子书阅读软件,以其良好的用户体验和丰富的书籍资源受到用户的喜爱。这个压缩包可能...