Android实用代码七段(四)

简介:

1、发送不重复的通知(Notification)

     public  static  void sendNotification(Context context, String title,
            String message, Bundle extras) {
        Intent mIntent =  new Intent(context, FragmentTabsActivity. class);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mIntent.putExtras(extras);

         int requestCode = ( int) System.currentTimeMillis();

        PendingIntent mContentIntent = PendingIntent.getActivity(context,
                requestCode, mIntent, 0);

        Notification mNotification =  new NotificationCompat.Builder(context)
                .setContentTitle(title).setSmallIcon(R.drawable.app_icon)
                .setContentIntent(mContentIntent).setContentText(message)
                .build();
        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotification.defaults = Notification.DEFAULT_ALL;

        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(requestCode, mNotification);
    }

代码说明:

关键点在这个requestCode,这里使用的是当前系统时间,巧妙的保证了每次都是一个新的Notification产生。 

2、代码设置TextView的样式

     使用过自定义Dialog可能马上会想到用如下代码:

new TextView(this,null,R.style.text_style); 

但你运行这代码你会发现毫无作用!正确用法:

new TextView( new ContextThemeWrapper( this, R.style.text_style))

来自这里。 

3、 ip地址转成8位十六进制串

     /**  ip转16进制  */
     public  static String ipToHex(String ips) {
        StringBuffer result =  new StringBuffer();
         if (ips !=  null) {
            StringTokenizer st =  new StringTokenizer(ips, ".");
             while (st.hasMoreTokens()) {
                String token = Integer.toHexString(Integer.parseInt(st.nextToken()));
                 if (token.length() == 1)
                    token = "0" + token;
                result.append(token);
            }
        }
         return result.toString();
    }

     /**  16进制转ip  */
     public  static String texToIp(String ips) {
         try {
            StringBuffer result =  new StringBuffer();
             if (ips !=  null && ips.length() == 8) {
                 for ( int i = 0; i < 8; i += 2) {
                     if (i != 0)
                        result.append('.');
                    result.append(Integer.parseInt(ips.substring(i, i + 2), 16));
                }
            }
             return result.toString();
        }  catch (NumberFormatException ex) {
            Logger.e(ex);
        }
         return "";
    }

ip:192.168.68.128 16 =>hex :c0a84480

4、WebView保留缩放功能但隐藏缩放控件

        mWebView.getSettings().setSupportZoom( true);
        mWebView.getSettings().setBuiltInZoomControls( true);
         if (DeviceUtils.hasHoneycomb())
              mWebView.getSettings().setDisplayZoomControls( false);

注意:setDisplayZoomControls是在API Level 11中新增。

5、获取网络类型名称

     public  static String getNetworkTypeName(Context context) {
         if (context !=  null) {
            ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             if (connectMgr !=  null) {
                NetworkInfo info = connectMgr.getActiveNetworkInfo();
                 if (info !=  null) {
                     switch (info.getType()) {
                     case ConnectivityManager.TYPE_WIFI:
                         return "WIFI";
                     case ConnectivityManager.TYPE_MOBILE:
                         return getNetworkTypeName(info.getSubtype());
                    }
                }
            }
        }
         return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN);
    }

     public  static String getNetworkTypeName( int type) {
         switch (type) {
         case TelephonyManager.NETWORK_TYPE_GPRS:
             return "GPRS";
         case TelephonyManager.NETWORK_TYPE_EDGE:
             return "EDGE";
         case TelephonyManager.NETWORK_TYPE_UMTS:
             return "UMTS";
         case TelephonyManager.NETWORK_TYPE_HSDPA:
             return "HSDPA";
         case TelephonyManager.NETWORK_TYPE_HSUPA:
             return "HSUPA";
         case TelephonyManager.NETWORK_TYPE_HSPA:
             return "HSPA";
         case TelephonyManager.NETWORK_TYPE_CDMA:
             return "CDMA";
         case TelephonyManager.NETWORK_TYPE_EVDO_0:
             return "CDMA - EvDo rev. 0";
         case TelephonyManager.NETWORK_TYPE_EVDO_A:
             return "CDMA - EvDo rev. A";
         case TelephonyManager.NETWORK_TYPE_EVDO_B:
             return "CDMA - EvDo rev. B";
         case TelephonyManager.NETWORK_TYPE_1xRTT:
             return "CDMA - 1xRTT";
         case TelephonyManager.NETWORK_TYPE_LTE:
             return "LTE";
         case TelephonyManager.NETWORK_TYPE_EHRPD:
             return "CDMA - eHRPD";
         case TelephonyManager.NETWORK_TYPE_IDEN:
             return "iDEN";
         case TelephonyManager.NETWORK_TYPE_HSPAP:
             return "HSPA+";
         default:
             return "UNKNOWN";
        }
    }

6、Android解压Zip包

     /**
     * 解压一个压缩文档 到指定位置
     * 
     * 
@param  zipFileString 压缩包的名字
     * 
@param  outPathString 指定的路径
     * 
@throws  Exception
     
*/
     public  static  void UnZipFolder(String zipFileString, String outPathString)  throws Exception {
        java.util.zip.ZipInputStream inZip =  new java.util.zip.ZipInputStream( new java.io.FileInputStream(zipFileString));
        java.util.zip.ZipEntry zipEntry;
        String szName = "";

         while ((zipEntry = inZip.getNextEntry()) !=  null) {
            szName = zipEntry.getName();

             if (zipEntry.isDirectory()) {

                 //  get the folder name of the widget
                szName = szName.substring(0, szName.length() - 1);
                java.io.File folder =  new java.io.File(outPathString + java.io.File.separator + szName);
                folder.mkdirs();

            }  else {

                java.io.File file =  new java.io.File(outPathString + java.io.File.separator + szName);
                file.createNewFile();
                 //  get the output stream of the file
                java.io.FileOutputStream out =  new java.io.FileOutputStream(file);
                 int len;
                 byte[] buffer =  new  byte[1024];
                 //  read (len) bytes into buffer
                 while ((len = inZip.read(buffer)) != -1) {
                     //  write (len) byte from buffer at the position 0
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        } // end of while

        inZip.close();

    } // end of func

7、 从assets中读取文本和图片资源

     /**  从assets 文件夹中读取文本数据  */
     public  static String getTextFromAssets( final Context context, String fileName) {
        String result = "";
         try {
            InputStream in = context.getResources().getAssets().open(fileName);
             //  获取文件的字节数
             int lenght = in.available();
             //  创建byte数组
             byte[] buffer =  new  byte[lenght];
             //  将文件中的数据读到byte数组中
            in.read(buffer);
            result = EncodingUtils.getString(buffer, "UTF-8");
            in.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
         return result;
    }
    
     /**  从assets 文件夹中读取图片  */
     public  static Drawable loadImageFromAsserts( final Context ctx, String fileName) {
         try {
            InputStream is = ctx.getResources().getAssets().open(fileName);
             return Drawable.createFromStream(is,  null);
        }  catch (IOException e) {
             if (e !=  null) {
                e.printStackTrace();
            }
        }  catch (OutOfMemoryError e) {
             if (e !=  null) {
                e.printStackTrace();
            }
        }  catch (Exception e) {
             if (e !=  null) {
                e.printStackTrace();
            }
        }
         return  null;
    }

系列

Android实用代码七段(三) 

Android实用代码七段(二)  

Android实用代码七段(一)  

本文转自博客园农民伯伯的博客,原文链接:Android实用代码七段(四),如需转载请自行联系原博主。



目录
相关文章
|
3天前
|
JSON JavaScript 前端开发
Android调用Vue中的JavaScript代码
Android调用Vue中的JavaScript代码
10 3
|
28天前
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
很多文章都介绍了FTPClient如何连接ftp服务器,但却很少有人说如何连接一台开了SSL认证的ftp服务器,现在代码来了。
61 2
|
10天前
|
Java Android开发
Android项目架构设计问题之要提升代码的可读性和管理性如何解决
Android项目架构设计问题之要提升代码的可读性和管理性如何解决
17 0
|
2月前
|
存储 Java Android开发
🔥Android开发大神揭秘:从菜鸟到高手,你的代码为何总是慢人一步?💻
【7月更文挑战第28天】在Android开发中,每位开发者都追求极致的用户体验。然而,“代码执行慢”的问题时常困扰着开发者。通过案例分析,我们可探索从新手到高手的成长路径。
29 3
|
2月前
|
API Android开发
Android 监听Notification 被清除实例代码
Android 监听Notification 被清除实例代码
|
3月前
|
JavaScript 前端开发 Android开发
kotlin安卓在Jetpack Compose 框架下使用webview , 网页中的JavaScript代码如何与native交互
在Jetpack Compose中使用Kotlin创建Webview组件,设置JavaScript交互:`@Composable`函数`ComposableWebView`加载网页并启用JavaScript。通过`addJavascriptInterface`添加`WebAppInterface`类,允许JavaScript调用Android方法如播放音频。当页面加载完成时,执行`onWebViewReady`回调。
140 2
|
2月前
|
Web App开发 JavaScript 前端开发
Android端使用WebView注入一段js代码实现js调用android
Android端使用WebView注入一段js代码实现js调用android
40 0
|
4月前
|
移动开发 监控 Android开发
构建高效Android应用:从内存优化到电池寿命代码之美:从功能实现到艺术创作
【5月更文挑战第28天】 在移动开发领域,特别是针对Android系统,性能优化始终是关键议题之一。本文深入探讨了如何通过细致的内存管理和电池使用策略,提升Android应用的运行效率和用户体验。文章不仅涵盖了现代Android设备上常见的内存泄漏问题,还提出了有效的解决方案,包括代码级优化和使用工具进行诊断。同时,文中也详细阐述了如何通过减少不必要的后台服务、合理管理设备唤醒锁以及优化网络调用等手段延长应用的电池续航时间。这些方法和技术旨在帮助开发者构建更加健壮、高效的Android应用程序。
|
3月前
|
存储 算法 Java
Android 进阶——代码插桩必知必会&ASM7字节码操作
Android 进阶——代码插桩必知必会&ASM7字节码操作
132 0
|
3月前
|
开发工具 Android开发
Android 代码自定义drawble文件实现View圆角背景
Android 代码自定义drawble文件实现View圆角背景
92 0