zoukankan      html  css  js  c++  java
  • ReadingNotes@02122013

    ReadingNotes@02-12-2013

    ReadingNotes@02-12-2013

    Cheatsheet: 2013 04.17 ~ 04.30

    一直都比较喜欢CheatSheet形式的reference,简单明了。

    这个不错Android cheatsheet for graphic designers

    C++ Macro

    http://stackoverflow.com/questions/216875/in-macros

    One thing to be aware of when you're using the token-paste ('##') or stringizing ('#') preprocessing operators is that you have to use an extra level of indirection for them to work properly in all cases

    实现类似android市场多apk同时下载,更新通知栏信息小结

    public class UpdateService extends Service {
        private NotificationManager nm;
        private Notification notification;
        private boolean cancelUpdate = false;
        private MyHandler myHandler;
        private static ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            /*同一个服务,为避免通知栏起冲突,特使用应用的id作为通知栏id,并用application中的一个Map记录id和下载进度,
            并通过handler操作*/
            int notificationId = intent.getIntExtra("id", new Random().nextInt());
            if(Constants.download.containsKey(notificationId))
                return 0;
            notification = new Notification();
            notification.icon = android.R.drawable.stat_sys_download;
            // notification.icon=android.R.drawable.stat_sys_download_done;
            notification.tickerText = intent.getStringExtra("name")+"开始下载";
            notification.when = System.currentTimeMillis();
            notification.defaults = Notification.DEFAULT_LIGHTS;
            //显示在“正在进行中”
            notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
            PendingIntent contentIntent = PendingIntent.getActivity(this, notificationId,new Intent(this, IndexActivity.class), 0);
            notification.setLatestEventInfo(this, intent.getStringExtra("name"), "0%", contentIntent);
            Constants.download.put(notificationId, 0);
            // 将下载任务添加到任务栏中
            nm.notify(notificationId, notification);
            myHandler = new MyHandler(Looper.myLooper(), UpdateService.this);
            //myHandler = new MyHandler(Looper.myLooper(), this);
    
            // 初始化下载任务内容views
            //Message message = myHandler.obtainMessage(3, 0);
            //myHandler.sendMessage(message);
    
            // 启动线程开始执行下载任务
            downFile(intent.getStringExtra("url"),notificationId,intent.getStringExtra("name"));
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
        }
    
        // 下载更新文件
        private void downFile(final String url,final int notificationId,final String name) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    File tempFile = null;
                    try {
                        HttpClient client = new DefaultHttpClient();
                        // params[0]代表连接的url
                        HttpGet get = new HttpGet(url);
                        HttpResponse response = client.execute(get);
                        HttpEntity entity = response.getEntity();
                        long length = entity.getContentLength();
                        InputStream is = entity.getContent();
                        if (is != null) {
                            File rootFile = new File(Environment.getExternalStorageDirectory(),"/zhtrade");
                            if (!rootFile.exists() && !rootFile.isDirectory())
                                rootFile.mkdir();
    
                            /*
                             * 路径的特殊性,分解出包名,并用对应的应用"_"+id特别标识,避免出现apk包重复和冲突(有一些apk的package是相同的)
                             */
                            tempFile = new File(Environment.getExternalStorageDirectory(),"/zhtrade/"+ url.substring(url.lastIndexOf("/"),url.indexOf("?"))+"_"+notificationId+".apk");
                            if (tempFile.exists())
                                tempFile.delete();
                            tempFile.createNewFile();
    
                            // 已读出流作为参数创建一个带有缓冲的输出流
                            BufferedInputStream bis = new BufferedInputStream(is);
    
                            // 创建一个新的写入流,讲读取到的图像数据写入到文件中
                            FileOutputStream fos = new FileOutputStream(tempFile);
                            // 已写入流作为参数创建一个带有缓冲的写入流
                            BufferedOutputStream bos = new BufferedOutputStream(fos);
    
                            int read;
                            long count = 0;
                            int precent = 0;
                            byte[] buffer = new byte[1024];
                            while ((read = bis.read(buffer)) != -1 && !cancelUpdate) {
                                bos.write(buffer, 0, read);
                                count += read;
                                precent = (int) (((double) count / length) * 100);
    
                                // 每下载完成10%就通知任务栏进行修改下载进度
                                if (precent - Constants.download.get(notificationId) >= 10) {
                                    Constants.download.put(notificationId, precent);
                                    Message message = myHandler.obtainMessage(3,precent);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("name", name);
                                    message.setData(bundle);
                                    message.arg1 = notificationId;
                                    myHandler.sendMessage(message);
                                }
                            }
                            bos.flush();
                            bos.close();
                            fos.flush();
                            fos.close();
                            is.close();
                            bis.close();
                        }
    
                        if (!cancelUpdate) {
                            Message message = myHandler.obtainMessage(2, tempFile);
                            message.arg1 = notificationId;
                            Bundle bundle = new Bundle();
                            bundle.putString("name", name);
                            message.setData(bundle);
                            myHandler.sendMessage(message);
                        } else {
                            tempFile.delete();
                        }
                    } catch (ClientProtocolException e) {
                        if (tempFile.exists())
                            tempFile.delete();
                        Message message = myHandler.obtainMessage(4, name+"下载失败:网络异常!");
                        message.arg1 = notificationId;
                        myHandler.sendMessage(message);
                    } catch (IOException e) {
                        if (tempFile.exists())
                            tempFile.delete();
                        Message message = myHandler.obtainMessage(4, name+"下载失败:文件存储异常");
                        message.arg1 = notificationId;
                        myHandler.sendMessage(message);
                    } catch (Exception e) {
                        if (tempFile.exists())
                            tempFile.delete();
                        Message message = myHandler.obtainMessage(4, name+"下载失败,"+e.getMessage());
                        message.arg1 = notificationId;
                        myHandler.sendMessage(message);
                    }
                }
            });
        }
    
        // 安装下载后的apk文件
        private void Instanll(File file, Context context) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    
        /* 事件处理类 */
        class MyHandler extends Handler {
            private Context context;
    
            public MyHandler(Looper looper, Context c) {
                super(looper);
                this.context = c;
            }
    
            @Override
            public void handleMessage(Message msg) {
                PendingIntent contentIntent = null;
                super.handleMessage(msg);
                if (msg != null) {
                    switch (msg.what) {
                    case 0:
                        Toast.makeText(context, msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        Constants.download.remove(msg.arg1);
                        break;
                    case 1:
                        break;
                    case 2:
                        contentIntent = PendingIntent.getActivity(UpdateService.this, msg.arg1,new Intent(UpdateService.this, IndexActivity.class), 0);
                        notification.setLatestEventInfo(UpdateService.this, msg.getData().getString("name")+"下载完成",   "100%",contentIntent);
                        nm.notify(msg.arg1, notification);
                        // 下载完成后清除所有下载信息,执行安装提示
                        Constants.download.remove(msg.arg1);
                        nm.cancel(msg.arg1);
                        Instanll((File) msg.obj, context);
                        // 停止掉当前的服务
                        stopSelf();
                        break;
                    case 3:
                         contentIntent = PendingIntent.getActivity(UpdateService.this, msg.arg1,new Intent(UpdateService.this, IndexActivity.class), 0);
                        notification.setLatestEventInfo(UpdateService.this, msg.getData().getString("name")+"正在下载",  Constants.download.get(msg.arg1) + "%",contentIntent);
                        nm.notify(msg.arg1, notification);
                        break;
                    case 4:
                        Toast.makeText(context, msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        Constants.download.remove(msg.arg1);
                        nm.cancel(msg.arg1);
                        stopSelf();
                        break;
                    }
                }
            }
        }
        
    }
    

    Post by: Jalen Wang (转载请注明出处)

  • 相关阅读:
    python编码小记
    eventlet学习笔记
    python库文件路径
    paste deploy初探
    python浅拷贝与深拷贝
    Javascript basic knowledge
    用大数据学习心理学
    Postgres Database management operations
    Python Socket and WSGI Sample
    Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory错误处理
  • 原文地址:https://www.cnblogs.com/jalenwang/p/3055984.html
Copyright © 2011-2022 走看看