android 学习笔记


原文地址:http://blog.csdn.net/yudajun/article/details/9119747

apk代码混淆保护4.0

# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
proguard.config=${sdk.dir}/tools/proguard/proguard-android-optimize.txt:proguard-project.txt
# Project target.
target=android-17

如果有报异常,例如这样,
java.io.IOException: Please correct the above warnings first.
  at proguard.Initializer.execute(Initializer.java:308)
  at proguard.ProGuard.initialize(ProGuard.java:210)
  at proguard.ProGuard.execute(ProGuard.java:85)
  at proguard.ProGuard.main(ProGuard.java:499)


这是由于第三方jar包的原因哦,

你可以这样,
${sdk.dir}\tools\proguard\proguard-android.txt中加入
-dontwarn com.aa.bb.*

-keep class com.aa.bb.*{ *;}

判断指定的服务是否运行:

[java]  view plain copy
  1. public static boolean isServiceRunning(Context ctx, String serviceName, String processName) {  
  2.         ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);  
  3.         for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {  
  4.             if (serviceName.equals(service.service.getClassName()) && processName.equals(service.process))  
  5.                 return true;  
  6.         }  
  7.         return false;  
  8.     }  

判断指定进程是否正在运行:

[java]  view plain copy
  1. public static boolean isProcessRunning(Context ctx, String name) {  
  2.         ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);  
  3.         List<RunningAppProcessInfo> apps = am.getRunningAppProcesses();  
  4.         for (RunningAppProcessInfo app : apps) {  
  5.             if (app.processName.equals(name)) {  
  6.                 return true;  
  7.             }  
  8.         }  
  9.         return false;  
  10.     }  

汉字转拼音:
百度搜素pinyin4j.jar 获取官网下载。添加至lib中

[java]  view plain copy
  1. /** 
  2.  * 汉字转换为拼音 
  3.  * @author Administrator 
  4.  * 
  5.  */   
  6. public class HanZiToPinYinUtil {    
  7.    
  8.      public static String toPinYin(String str) {     
  9.             String py = "";     
  10.             String[] t = new String[str.length()];     
  11.             char [] hanzi=new char[str.length()];     
  12.             for(int i=0;i<str.length();i++){     
  13.                 hanzi[i]=str.charAt(i);     
  14.             }     
  15.                  
  16.             net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t1 = new HanyuPinyinOutputFormat();     
  17.             t1.setCaseType(HanyuPinyinCaseType.LOWERCASE);     
  18.             t1.setToneType(HanyuPinyinToneType.WITHOUT_TONE);     
  19.             t1.setVCharType(HanyuPinyinVCharType.WITH_V);     
  20.                  
  21.             try {     
  22.                 for (int i = 0; i < str.length(); i++) {     
  23.                     if ((str.charAt(i) >= 'a' && str.charAt(i) < 'z')     
  24.                             || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')     
  25.                             || (str.charAt(i) >= '0' && str.charAt(i) <= '9')) {     
  26.                         py += str.charAt(i);     
  27.                     } else {     
  28.                             t = PinyinHelper.toHanyuPinyinStringArray(hanzi[i], t1);     
  29.                             py=py+t[0];     
  30.                         }     
  31.                     }     
  32.             } catch (BadHanyuPinyinOutputFormatCombination e) {     
  33.                 e.printStackTrace();     
  34.             }     
  35.          
  36.             return py.trim().toString();     
  37.         }     
  38.              
  39.      public static void main(String args[]){     
  40.             
  41.             System.out.println(HanZiToPinYinUtil.toPinYin("我屮艸芔茻"));      
  42.            
  43.      }     

开启飞行模式:

[java]  view plain copy
  1. boolean isEnabled = Settings.System.getInt(  
  2.                 paramContext.getContentResolver(),   
  3.                   Settings.System.AIRPLANE_MODE_ON, 0) == 1;  
  4.         if(isEnabled==true)  
  5.         {  
  6.             Settings.System.putInt(  
  7.                     paramContext.getContentResolver(),  
  8.                   Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);  
  9.   
  10.             // Post an intent to reload  
  11.             Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);  
  12.             intent.putExtra("state", !isEnabled);  
  13.             paramContext.sendBroadcast(intent);  
  14.         }  
  15.         else  
  16.         {  
  17.             Settings.System.putInt(  
  18.                     paramContext.getContentResolver(),  
  19.                   Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);  
  20.   
  21.             // Post an intent to reload  
  22.             Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);  
  23.             intent.putExtra("state", !isEnabled);  
  24.             paramContext.sendBroadcast(intent);  
  25.         }  
  26.           
  27.   
  28. <uses-permission android:name="android.permission.WRITE_SETTINGS"/>  
  29. <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>  


开机自启动:(注意:app一定要安装到内存中,在sd卡上无法自启动)

[java]  view plain copy
  1. <receiver android:name="com.pioneersoft.aoc.ui.BootBroadcastReceiver" android:enabled="true" android:exported="true">  
  2.             <intent-filter >  
  3.                 <action android:name="android.intent.action.BOOT_COMPLETED" />  
  4.                 <category android:name="android.intent.category.HOME" />  
  5.             </intent-filter>  
  6.         </receiver>  

[java]  view plain copy
  1. public class BootBroadcastReceiver extends BroadcastReceiver {  
  2.   
  3. //  static final String action_boot="android.intent.action.BOOT_COMPLETED";  
  4.        
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.  //       if (intent.getAction().equals(action_boot)){  
  8.             Intent bootStartIntent=new Intent(context,MainActivity.class);  
  9.             bootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  10.             context.startActivity(bootStartIntent);  
  11. //        }  
  12.    
  13.     }  
  14. }  

获取未安装apk信息:

[java]  view plain copy
  1. /** 获取未安装的APK信息   
  2.      * @param context   
  3.      * @param archiveFilePath APK文件的路径。如:/sdcard /download/XX.apk   
  4.      */      
  5.     public void getUninatllApkInfo(Context context, String archiveFilePath){      
  6.         PackageManager pm = context.getPackageManager();      
  7.         PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);      
  8.         if(info != null){      
  9.             ApplicationInfo appInfo = info.applicationInfo;      
  10.             String appName = pm.getApplicationLabel(appInfo).toString();      
  11.             String packageName = appInfo.packageName;      
  12.             Drawable icon = pm.getApplicationIcon(appInfo);      
  13.         }      
  14.     }    

监听apk安装,卸载,替换行为:

[java]  view plain copy
  1. private void registerIntentReceivers() {  
  2.         IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);  
  3.         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);  
  4.         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);  
  5.         filter.addAction(Intent.ACTION_PACKAGE_REPLACED);  
  6.         filter.addDataScheme("package");  
  7.         registerReceiver(mApplicationsReceiver, filter);  
  8.     }  
  9.      /** 
  10.      * Receives notifications when applications are added/removed. 
  11.      */  
  12.     private class ApplicationsIntentReceiver extends BroadcastReceiver {  
  13.         @Override  
  14.         public void onReceive(Context context, Intent intent) {  
  15.         //   PackageManager manager = context.getPackageManager();  
  16.               
  17.              if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {  
  18.                  String packageName = intent.getData().getSchemeSpecificPart();  
  19.                  Toast.makeText(context, "安装成功"+packageName, Toast.LENGTH_LONG).show();  
  20.              }  
  21.              if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {  
  22.                  String packageName = intent.getData().getSchemeSpecificPart();  
  23.                  Toast.makeText(context, "卸载成功"+packageName, Toast.LENGTH_LONG).show();  
  24.              }  
  25.              if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {  
  26.                  String packageName = intent.getData().getSchemeSpecificPart();  
  27.                  Toast.makeText(context, "替换成功"+packageName, Toast.LENGTH_LONG).show();  
  28.              }  
  29.         }  
  30.     }  



loadData()中的html data中不能包含'#', '%', '\', '?'四中特殊字符,出现这种字符就会出现解析错误,显示找不到网页还有部分html代码。需要如何处理呢?我们需要用UrlEncoder编码为%23, %25, %27, %3f 。
可以使用以下两种代码,data为string类型的html代码
1     webView.loadData(URLEncoder.encode(data, "utf-8"), "text/html",  "utf-8");
这样一些背景效果什么的都不怎么好看了。不推荐。
2     webView.loadDataWithBaseURL(null,data, "text/html",  "utf-8", null);

这样就会完美解析了。


计算网络接收byte[] 字节数组的实际接受内容大小:

[java]  view plain copy
  1. public static void main(String[] args) {  
  2.         byte[] bt=new byte[1024];  
  3.         String msg="helo! you are very nice! have a good time! happy every day!";  
  4.         byte[] t=msg.getBytes();  
  5.           
  6.         for(int i=0;i<t.length;i++){  
  7.             bt[i]=t[i];  
  8.         }  
  9.         String message=new String(bt).trim();   
  10.           
  11.         System.out.println(" msg= "+message+" len= "+message.length());  
  12.     }  

获取现在正调用的方法名

[java]  view plain copy
  1. String methodName =  
  2. Thread.currentThread().getStackTrace()[1].getMethodName();    
  3. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();  


[java]  view plain copy
  1. /** 
  2.      * 安装app 
  3.      */  
  4.     public static void openAPK(File f, Context context) {  
  5.         context.startActivity(getInstallApp(f, context));  
  6.     }  
  7.   
  8.   
  9.     public static Intent getInstallApp(File f, Context context) {  
  10.         Intent intent = new Intent();  
  11.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  12.             //设置应用的安装来源,例如谷歌市场  
  13.         intent.putExtra("android.intent.extra.INSTALLER_PACKAGE_NAME", context.getPackageName());  
  14.         intent.setAction(android.content.Intent.ACTION_VIEW);  
  15.   
  16.   
  17.         /* 设置intent的file */  
  18.         intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive");  
  19.         return intent;  
  20.     }  
  21.     /** 
  22.      * 卸载APP 
  23.      * @param context 
  24.      * @param packageName 
  25.      */  
  26.     public static void uninstallApp(Context context,String packageName) {  
  27.         Uri packageURI = Uri.parse("package:" + packageName);     
  28.         Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);     
  29.         uninstallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  30.         context.startActivity(uninstallIntent);  
  31.     }  


[java]  view plain copy
  1. Android屏幕解锁和锁定  
  2.   //屏幕解锁  
  3.   KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);  
  4.   KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(LOCK_TAG);  
  5.   keyguardLock.disableKeyguard();  
  6.   
  7.   
  8.   //屏幕锁定  
  9.   keyguardLock.reenableKeyguard();  
  10.   
  11.   
  12.   Android屏幕常亮/点亮  
  13.   //保持屏幕常亮  
  14.   PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
  15.   mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOCK_TAG);    
  16.   mWakeLock.acquire();  
  17.   
  18.   
  19.   //释放屏幕常亮锁  
  20.   if(null != mWakeLock) {  
  21.       mWakeLock.release();  
  22.   }  
  23.   
  24.   
  25. /** 
  26.      * 判断桌面是否已添加快捷方式 
  27.      *  
  28.      * @param cx 
  29.      * @param titleName 
  30.      *            快捷方式名称 
  31.      * @return 
  32.      */  
  33.     public static boolean hasShortcut(Context cx) {  
  34.         boolean result = false;  
  35.         // 获取当前应用名称  
  36.         String title = null;  
  37.         try {  
  38.             final PackageManager pm = cx.getPackageManager();  
  39.             title = pm.getApplicationLabel(  
  40.                     pm.getApplicationInfo(cx.getPackageName(),  
  41.                             PackageManager.GET_META_DATA)).toString();  
  42.         } catch (Exception e) {  
  43.         }  
  44.   
  45.   
  46.         final String uriStr;  
  47.         if (android.os.Build.VERSION.SDK_INT < 8) {  
  48.             uriStr = "content://com.android.launcher.settings/favorites?notify=true";  
  49.         } else {  
  50.             uriStr = "content://com.android.launcher2.settings/favorites?notify=true";  
  51.         }  
  52.         final Uri CONTENT_URI = Uri.parse(uriStr);  
  53.         final Cursor c = cx.getContentResolver().query(CONTENT_URI, null,  
  54.                 "title=?"new String[] { title }, null);  
  55.         if (c != null && c.getCount() > 0) {  
  56.             result = true;  
  57.         }  
  58.         return result;  
  59.     }  
  60.   
  61.  /** * 
  62.     * 为当前应用添加桌面快捷方式 
  63.     *  
  64.     * @param cx 
  65.     * @param appName 
  66.     *            快捷方式名称 
  67.     */  
  68.    public static void addShortcut(Context cx) {  
  69.        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");  
  70.   
  71.   
  72.        Intent shortcutIntent = cx.getPackageManager()  
  73.                .getLaunchIntentForPackage(cx.getPackageName());  
  74.        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);  
  75.        // 获取当前应用名称  
  76.        String title = null;  
  77.        try {  
  78.            final PackageManager pm = cx.getPackageManager();  
  79.            title = pm.getApplicationLabel(  
  80.                    pm.getApplicationInfo(cx.getPackageName(),  
  81.                            PackageManager.GET_META_DATA)).toString();  
  82.        } catch (Exception e) {  
  83.        }  
  84.        // 快捷方式名称  
  85.        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);  
  86.        // 不允许重复创建(不一定有效)  
  87.        shortcut.putExtra("duplicate"false);  
  88.        // 快捷方式的图标  
  89.        Parcelable iconResource = Intent.ShortcutIconResource.fromContext(cx,  
  90.                R.drawable.ic_launcher);  
  91.        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);  
  92.   
  93.   
  94.        cx.sendBroadcast(shortcut);  
  95.    }  
  96.   
  97.  /*** 
  98.     * 删除当前应用的桌面快捷方式 
  99.     *  
  100.     * @param cx 
  101.     */  
  102.    public static void delShortcut(Context cx) {  
  103.        Intent shortcut = new Intent(  
  104.                "com.android.launcher.action.UNINSTALL_SHORTCUT");  
  105.   
  106.   
  107.        // 获取当前应用名称  
  108.        String title = null;  
  109.        try {  
  110.            final PackageManager pm = cx.getPackageManager();  
  111.            title = pm.getApplicationLabel(  
  112.                    pm.getApplicationInfo(cx.getPackageName(),  
  113.                            PackageManager.GET_META_DATA)).toString();  
  114.        } catch (Exception e) {  
  115.        }  
  116.        // 快捷方式名称  
  117.        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);  
  118.        Intent shortcutIntent = cx.getPackageManager()  
  119.                .getLaunchIntentForPackage(cx.getPackageName());  
  120.        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);  
  121.        cx.sendBroadcast(shortcut);  
  122.    }  
  123.   
  124. 相关权限配置  
  125.     <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />  
  126.     <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />  
  127.     <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />  


每个月的第几号执行提醒功能:

[java]  view plain copy
  1. Calendar cal = Calendar.getInstance();  
  2.   
  3.     cal.set(Calendar.DAY_OF_MONTH, 4);  
  4.     cal.set(Calendar.HOUR_OF_DAY, 10);  
  5.     cal.set(Calendar.MINUTE, 0);  
  6.     cal.set(Calendar.SECOND, 0);  
  7.     Date now = new Date(System.currentTimeMillis());  
  8.     if (cal.getTime().before(now)) {  
  9.         cal.add(Calendar.MONTH, 1);  
  10.     }  
  11.     long firstTime = cal.getTime().getTime();  
  12.      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 1000 * 60  
  13.             * 60 * 24 * 30, pendingIntent);  


上传应用到服务器:

[java]  view plain copy
  1. private String newName = "htys.mp3";  
  2.   //要上传的本地文件路径  
  3.   private String uploadFile = "/data/data/com.xzq/htys.mp3";  
  4.   //上传到服务器的指定位置  
  5.   private String actionUrl = "http://192.168.100.100:8080/upload/upload.jsp";  

[java]  view plain copy
  1. private void uploadFile()  
  2.   {  
  3.     String end = "/r/n";  
  4.     String Hyphens = "--";  
  5.     String boundary = "*****";  
  6.     try  
  7.     {  
  8.       URL url = new URL(actionUrl);  
  9.       HttpURLConnection con = (HttpURLConnection) url.openConnection();  
  10.        
  11.       con.setDoInput(true);  
  12.       con.setDoOutput(true);  
  13.       con.setUseCaches(false);  
  14.        
  15.       con.setRequestMethod("POST");  
  16.        
  17.       con.setRequestProperty("Connection""Keep-Alive");  
  18.       con.setRequestProperty("Charset""UTF-8");  
  19.       con.setRequestProperty("Content-Type",  
  20.           "multipart/form-data;boundary=" + boundary);  
  21.        
  22.       DataOutputStream ds = new DataOutputStream(con.getOutputStream());  
  23.       ds.writeBytes(Hyphens + boundary + end);  
  24.       ds.writeBytes("Content-Disposition: form-data; "  
  25.           + "name=/"file1/";filename=/"" + newName + "/"" + end);  
  26.       ds.writeBytes(end);  
  27.        
  28.       FileInputStream fStream = new FileInputStream(uploadFile);  
  29.        
  30.       int bufferSize = 1024;  
  31.       byte[] buffer = new byte[bufferSize];  
  32.       int length = -1;  
  33.        
  34.       while ((length = fStream.read(buffer)) != -1)  
  35.       {  
  36.          
  37.         ds.write(buffer, 0, length);  
  38.       }  
  39.       ds.writeBytes(end);  
  40.       ds.writeBytes(Hyphens + boundary + Hyphens + end);  
  41.       fStream.close();  
  42.       ds.flush();  
  43.        
  44.       InputStream is = con.getInputStream();  
  45.       int ch;  
  46.       StringBuffer b = new StringBuffer();  
  47.       while ((ch = is.read()) != -1)  
  48.       {  
  49.         b.append((char) ch);  
  50.       }  
  51.       System.out.println("上传成功");  
  52.       Toast.makeText(MainActivity.this"上传成功", Toast.LENGTH_LONG)  
  53.           .show();  
  54.       ds.close();  
  55.     } catch (Exception e)  
  56.     {  
  57.       System.out.println("上传失败" + e.getMessage());  
  58.       Toast.makeText(MainActivity.this"上传失败" + e.getMessage(),  
  59.           Toast.LENGTH_LONG).show();  
  60.     }  
  61.   }  
  62. }  

创建两个对话框模式进度样式:

ProgressDialog pdialog = new ProgressDialog(SettingActivity.this,0);


ScrollView 嵌套 ListView GridView问题

[java]  view plain copy
  1. public class MyListView extends ListView{  
  2.  public MyListView(Context context, AttributeSet attrs) {  
  3.         super(context, attrs);  
  4.     }  
  5.     public MyListView(Context context) {  
  6.         super(context);  
  7.     }  
  8.     public MyListView(Context context, AttributeSet attrs, int defStyle) {  
  9.         super(context, attrs, defStyle);  
  10.     }  
  11.     @Override  
  12.     public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  13.         int expandSpec = MeasureSpec.makeMeasureSpec(  
  14.                 Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);  
  15.         super.onMeasure(widthMeasureSpec, expandSpec);  
  16.     }  
  17. }  


设置texview 垂直滚动条

<TextView
      android:focusable="true"
      android:focusableInTouchMode="true"
      android:ellipsize="marquee"
      android:marqueeRepeatLimit="marquee_forever"
      android:scrollbars="vertical"        
      android:singleLine="false" />
 

设置textview 文字水平自动滚动(跑马灯效果)

<com.example.playpic.MyTextView
        android:id="@+id/myTv"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#000000"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        />

布局文件需添加属性:android:addStatesFromChildren="true"
修改的textview

[java]  view plain copy
  1. public class MyTextView extends TextView {  
  2.   
  3.     public MyTextView(Context context) {  
  4.         super(context);  
  5.     }  
  6.       
  7.     public MyTextView(Context context, AttributeSet attrs) {  
  8.         super(context, attrs);  
  9.     }  
  10.       
  11.     public MyTextView(Context context, AttributeSet attrs, int defStyle) {  
  12.         super(context, attrs, defStyle);  
  13.     }  
  14.       
  15.     @Override  
  16.     protected void onDraw(Canvas canvas) {  
  17.         super.onDraw(canvas);  
  18.     }  
  19.     @Override  
  20.     public boolean isFocused() {  
  21.         return true;  
  22.     }  
  23.   
  24. }  
  25.   
  26. setContentView(R.layout.scrollview1);  
  27.         MyTextView tv=(MyTextView)findViewById(R.id.myTv);  
  28.         tv.setText(str);  
  29.         tv.setMovementMethod(ScrollingMovementMethod.getInstance());  

大数据量提高sqlite数据存储效率:
在开发过程中解析xml中的数据有上万条之多,发现在想sqlite中插入的时候非常耗时,原因是没有使用事务,默认是每插入一次使用
一次事务,这样如果插入1w条数据,就要开启1w次事务,非常耗时,所以我们可以通过手动开启和关闭的方式控制事务。

[java]  view plain copy
  1. public void insertAll(String databaseName,    
  2.             ArrayList<ContentValues> valuesArr) {    
  3.         SQLiteDatabase db = getWritableDatabase();    
  4.         db.beginTransaction();    
  5.         for (ContentValues val : valuesArr) {    
  6.             db.insert(databaseName, null, val);    
  7.         }    
  8.     
  9.         db.setTransactionSuccessful();    
  10.         db.endTransaction();    
  11.         db.close();    
  12.     }    
 
计算日期之间相隔几天:

[java]  view plain copy
  1. public void t(){  
  2.   String before = "2013-5-15";  
  3.   String now = "2013-5-17";  
  4.   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  5.   try {  
  6.    Date d1 = sdf.parse(before);  
  7.    Date d2 = sdf.parse(now);  
  8.    long daysBetween = (d2.getTime() - d1.getTime() + 1000000)  
  9.      / (3600 * 24 * 1000);  
  10.    System.out.println("相隔:"+daysBetween+"天");  
  11.   } catch (Exception e) {  
  12.    System.out.println(e.getMessage());  
  13.   }  
  14.  }  

你可能感兴趣的:(android,代码混淆)