android 學習筆記有用程式碼片段(3)

來源:互聯網
上載者:User

設定texview 垂直捲軸

 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

public class MyTextView extends TextView {public MyTextView(Context context) {super(context);}public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);}public MyTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);}@Overridepublic boolean isFocused() {return true;}}

setContentView(R.layout.scrollview1);MyTextView tv=(MyTextView)findViewById(R.id.myTv);tv.setText(str);tv.setMovementMethod(ScrollingMovementMethod.getInstance());

大資料量提高sqlite資料存放區效率:

在開發過程中解析xml中的資料有上萬條之多,發現在想sqlite中插入的時候非常耗時,原因是沒有使用事務,預設是每插入一次使用

一次事務,這樣如果插入1w條資料,就要開啟1w次事務,非常耗時,所以我們可以通過手動開啟和關閉的方式控制事務。

public void insertAll(String databaseName,              ArrayList<ContentValues> valuesArr) {          SQLiteDatabase db = getWritableDatabase();          db.beginTransaction();          for (ContentValues val : valuesArr) {              db.insert(databaseName, null, val);          }            db.setTransactionSuccessful();          db.endTransaction();          db.close();      }  

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.txtproguard.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 中.class檔案保護

http://blog.sina.com.cn/s/blog_6dc41baf01010khy.html

開啟飛航模式:

boolean isEnabled = Settings.System.getInt(                paramContext.getContentResolver(),                   Settings.System.AIRPLANE_MODE_ON, 0) == 1;        if(isEnabled==true)        {            Settings.System.putInt(                    paramContext.getContentResolver(),                  Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);            // Post an intent to reload            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);            intent.putExtra("state", !isEnabled);            paramContext.sendBroadcast(intent);        }        else        {            Settings.System.putInt(                    paramContext.getContentResolver(),                  Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);            // Post an intent to reload            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);            intent.putExtra("state", !isEnabled);            paramContext.sendBroadcast(intent);        }

<uses-permission android:name="android.permission.WRITE_SETTINGS"/><uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>

漢字轉拼音:

百度搜素pinyin4j.jar 擷取官網下載。添加至lib中

/** * 漢字轉換為拼音 * @author Administrator * */ public class HanZiToPinYinUtil {        public static String toPinYin(String str) {               String py = "";               String[] t = new String[str.length()];               char [] hanzi=new char[str.length()];               for(int i=0;i<str.length();i++){                   hanzi[i]=str.charAt(i);               }                              net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat t1 = new HanyuPinyinOutputFormat();               t1.setCaseType(HanyuPinyinCaseType.LOWERCASE);               t1.setToneType(HanyuPinyinToneType.WITHOUT_TONE);               t1.setVCharType(HanyuPinyinVCharType.WITH_V);                              try {                   for (int i = 0; i < str.length(); i++) {                       if ((str.charAt(i) >= 'a' && str.charAt(i) < 'z')                               || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')                               || (str.charAt(i) >= '0' && str.charAt(i) <= '9')) {                           py += str.charAt(i);                       } else {                               t = PinyinHelper.toHanyuPinyinStringArray(hanzi[i], t1);                               py=py+t[0];                           }                       }               } catch (BadHanyuPinyinOutputFormatCombination e) {                   e.printStackTrace();               }                      return py.trim().toString();           }                   public static void main(String args[]){                         System.out.println(HanZiToPinYinUtil.toPinYin("我屮艸芔茻"));                  }   

指定下載連結,進行檔案下載功能:

public static void saveUrlAs(String Url, File fileName){        //此方法只能用HTTP協議        //儲存檔案到本地        //Url是檔案,fileName 為一個全名(路徑+檔案名稱)檔案        URL url;        DataOutputStream out = null;        DataInputStream in = null;        try {            url = new URL(Url);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            in = new DataInputStream(connection.getInputStream());            out = new DataOutputStream(new FileOutputStream(fileName));            byte[] buffer = new byte[4096];            int count = 0;                 while ((count = in.read(buffer)) > 0) {                     out.write(buffer, 0, count);                 }        }catch (Exception e) {            e.printStackTrace();        }finally{            try {                if(out != null){                    out.close();                }                if(in != null){                    in.close();                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }

計算日期之間相隔幾天:

public void t(){  String before = "2013-5-15";  String now = "2013-5-17";  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  try {   Date d1 = sdf.parse(before);   Date d2 = sdf.parse(now);   long daysBetween = (d2.getTime() - d1.getTime() + 1000000)     / (3600 * 24 * 1000);   System.out.println("相隔:"+daysBetween+"天");  } catch (Exception e) {   System.out.println(e.getMessage());  } }

java與c/c++ socket通訊漢字編碼解決方案:

// 發送socket資料,進行寫出                  dos = new DataOutputStream(mSocket.getOutputStream()); //              dos.writeUTF(s.trim() + "\n");                  dos.write(URLEncoder.encode(s, "GB2312").getBytes());                 dos.flush();  // 接收socket                  mSocket.getInputStream().read(receive);                 String ss = new String(receive); //              ss =ss.substring(0, ss.lastIndexOf("%02"));                  String data = URLDecoder.decode(ss, "GB2312");                 System.out.println(data);

判斷指定的服務是否運行:

public static boolean isServiceRunning(Context ctx, String serviceName, String processName) {ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {if (serviceName.equals(service.service.getClassName()) && processName.equals(service.process))return true;}return false;}

判斷指定進程是否正在運行:

public static boolean isProcessRunning(Context ctx, String name) {ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);List<RunningAppProcessInfo> apps = am.getRunningAppProcesses();for (RunningAppProcessInfo app : apps) {if (app.processName.equals(name)) {return true;}}return false;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.