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

來源:互聯網
上載者:User

隱去標題列,  隱去狀態列 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:theme="@android:style/Theme.Translucent" 
android:theme="@android:style/Theme.Dialog"

//初始化螢幕解析度
private void initDisplayMetrics()
{
  /* 取得螢幕解析度大小 */
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.width=dm.widthPixels;
        this.height=dm.heightPixels;
}

 //強製為橫屏   
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  
要設定成豎屏設定成 SCREEN_ORIENTATION_PORTRAIT

AndroidManifest.xml 中設定強制橫屏
<activity android:name=".HandlerActivity" android:screenOrientation="landscape"/>   

//強製為豎屏   
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
<activity android:name=".HandlerActivity" android:screenOrientation="portrait"/>
//將Activity設為視窗
<activity android:name=".Other"
android:theme="@android:style/Theme.Dialog" //android:theme=@style/Theme.FloatActivity
/>
AndroidManifest.xml 中設定屬性禁止重新建立Activity,並且添加螢幕切換監聽。
<activity android:name=".HandlerActivity"
sdk<3.2 android:configChanges="orientation|keyboardHidden"/>
dk>3.2 android:configChanges="orientation|screenSize"

@Override
public void onConfigurationChanged(Configuration newConfig) {

  int type = this.getResources().getConfiguration().orientation; 

 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {  

 } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { 
 
 }  

super.onConfigurationChanged(newConfig);
}

/** 判斷是否正在運行 */public static boolean isRunning(Context ctx,String name) {ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);for (RunningServiceInfo service : manager.getRunningServices(30)) {if (name.equals(service.service.getClassName()))return true;}return false;}

重啟應用

 Intent i = getBaseContext().getPackageManager()                  .getLaunchIntentForPackage(getBaseContext().getPackageName());          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);          startActivity(i);

判斷串連是否斷開:

方法一:

try {
socket.sendUrgentData(0xFF);
} catch (IOException e) {
//網路斷開
e.printStackTrace();
}

方法二:

try {
while(bconn){

String msg=dis.readUTF();
ta.setText(ta.getText()+msg+'\n');
}
} catch(SocketException e){
System.out.print("已經退出!");
} catch (IOException e) {
e.printStackTrace();
}

dip轉為px:

public static int dipToPX(final Context ctx, float dip) {        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, ctx.getResources().getDisplayMetrics());    }

檢查有沒有應用程式來接受處理你發出的intent

 public static boolean isIntentAvailable(Context context, String action) {        final PackageManager packageManager = context.getPackageManager();        final Intent intent = new Intent(action);        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);        return list.size() > 0;    }

檢測字串中是否包含漢字

public static boolean checkChinese(String sequence) {        final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";        boolean result = false;        Pattern pattern = Pattern.compile(format);        Matcher matcher = pattern.matcher(sequence);        result = matcher.find();        return result;    }

/** * 毫秒轉換幾分幾秒 * @param dur * @return */private String formatDuration(long dur){long min=dur/1000/60;long sec=dur/1000%60;return ""+min+"'"+sec+"\"";}/** * 位元組大小轉換成kb,mb * @param size * @return */private String formatSize(long size) {String suffix = null;if (size >= 1024) {suffix = "KB";size /= 1024;if (size >= 1024) {suffix = "MB";size /= 1024;}}StringBuilder resultBuffer = new StringBuilder(Long.toString(size));int commaOffset = resultBuffer.length() - 3;while (commaOffset > 0) {resultBuffer.insert(commaOffset, ',');commaOffset -= 3;}if (suffix != null)resultBuffer.append(suffix);return resultBuffer.toString();}

格式化時間:

 public static String generateTime(long time) {        int totalSeconds = (int) (time / 1000);        int seconds = totalSeconds % 60;        int minutes = (totalSeconds / 60) % 60;        int hours = totalSeconds / 3600;        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);    }

格式檔案大小:

public String formatSize(long size) {      String suffix = null;      float fSize=0;        if (size >= 1024) {          suffix = "KB";          fSize=size / 1024;          if (fSize >= 1024) {              suffix = "MB";              fSize /= 1024;          }          if (fSize >= 1024) {              suffix = "GB";              fSize /= 1024;          }      } else {          fSize = size;      }      java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");      StringBuilder resultBuffer = new StringBuilder(df.format(fSize));      if (suffix != null)          resultBuffer.append(suffix);      return resultBuffer.toString();  }  

擷取可以儲存卡可用空間:

public static String showFileSize(long size) {String fileSize;if (size < KB)fileSize = size + "B";else if (size < MB)fileSize = String.format("%.1f", size / KB) + "KB";else if (size < GB)fileSize = String.format("%.1f", size / MB) + "MB";elsefileSize = String.format("%.1f", size / GB) + "GB";return fileSize;}/** 顯示SD卡剩餘空間 */public static String showFileAvailable() {String result = "";if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getPath());long blockSize = sf.getBlockSize();long blockCount = sf.getBlockCount();long availCount = sf.getAvailableBlocks();return showFileSize(availCount * blockSize) + " / " + showFileSize(blockSize * blockCount);}return result;}

private static final double KB = 1024.0;private static final double MB = KB * KB;private static final double GB = KB * KB * KB;

計算文本,行數,高度
FontMetrics fm = mTextView.getPaint().getFontMetrics();
mFontHeight = (int) (Math.ceil(fm.descent - fm.top) + 2);// 獲得每行高度   

mPageLineNum = (int) (mTextHeight / mFontHeight);// 獲得行數

自訂view 中文本自動換行

private void drawText(Canvas canvas,String text){//clear screencanvas.drawRect(new Rect(0,0,getWidth(),getHeight()), backPaint);/*// draw text contentcanvas.drawText(text, posx, posy-step, textPaint);step+=10.0f;if (step > posy)step = 0;invalidate();*/ FontMetrics fm = textPaint.getFontMetrics(); float baseline = fm.descent - fm.ascent;  float x = 0; float y =  baseline;  //由於系統基於字型的底部來繪製文本,所有需要加上字型的高度        //文本自動換行 String[] texts = autoSplit(text, textPaint, getWidth() - 5);         for(String t : texts) {         canvas.drawText(t, x, y, textPaint);  //座標以控制項左上方為原點        y += baseline + fm.leading; //添加字型行間距    }}

/** * 自動分割文本 * @param content 需要分割的文本 * @param p  畫筆,用來根據字型測量文本的寬度 * @param width 最大的可顯示像素(一般為控制項的寬度) * @return 一個字串數組,儲存每行的文本 */private String[] autoSplit(String content, Paint p, float width) {    int length = content.length();    float textWidth = p.measureText(content);    if(textWidth <= width) {        return new String[]{content};    }            int start = 0, end = 1, i = 0;    int lines = (int) Math.ceil(textWidth / width); //計算行數    String[] lineTexts = new String[lines];    while(start < length) {        if(p.measureText(content, start, end) > width) { //文本寬度超出控制項寬度時            lineTexts[i++] = (String) content.subSequence(start, end);            start = end;        }        if(end == length) { //不足一行的文本            lineTexts[i] = (String) content.subSequence(start, end);            break;        }        end += 1;    }    return lineTexts;}

關閉後台進程:
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
activityManager.killBackgroundProcesses("name.of.your.package"); 
需要一個許可權:KILL_BACKGROUND_PROCESSES

擷取記憶體資訊:
ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
//可用記憶體
outInfo.availMem
//是否在低記憶體狀態
outInfo.lowMemory

擷取正在啟動並執行進程:

/** 擷取系統全域狀態. */
ActivityManager mActManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
/** 獲得系統正在啟動並執行進程. */
List<RunningAppProcessInfo> mAllSysAppProcesses = mActManager.getRunningAppProcesses();

媒體庫資料更新:

 public static void newFileNotify(String path) {        if (Defaults.do_mediascanner_notify) {            Log.d(TAG, "Notifying others about new file: " + path);            new MediaScannerNotifier(Globals.getContext(), path);        }    }    public static void deletedFileNotify(String path) {        // This might not work, I couldn't find an API call for this.        if (Defaults.do_mediascanner_notify) {            Log.d(TAG, "Notifying others about deleted file: " + path);            new MediaScannerNotifier(Globals.getContext(), path);        }    }    // A class to help notify the Music Player and other media services when    // a file has been uploaded.    private static class MediaScannerNotifier implements MediaScannerConnectionClient {        private final MediaScannerConnection connection;        private final String path;        public MediaScannerNotifier(Context context, String path) {            this.path = path;            connection = new MediaScannerConnection(context, this);            connection.connect();        }        public void onMediaScannerConnected() {            connection.scanFile(path, null); // null: we don't know MIME type        }        public void onScanCompleted(String path, Uri uri) {            connection.disconnect();        }    }

或者

// Tell the media scanner about the new file so that it is            // immediately available to the user.            MediaScannerConnection.scanFile(this,                    new String[] { file.toString() }, null,                    new MediaScannerConnection.OnScanCompletedListener() {                public void onScanCompleted(String path, Uri uri) {                    Log.i("ExternalStorage", "Scanned " + path + ":");                    Log.i("ExternalStorage", "-> uri=" + uri);                }            });

保持網路喚醒:

 private void takeWakeLock() {        if (wakeLock == null) {            Log.d(TAG, "About to take wake lock");            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);            // Many (all?) devices seem to not properly honor a            // PARTIAL_WAKE_LOCK,            // which should prevent CPU throttling. This has been            // well-complained-about on android-developers.            // For these devices, we have a config option to force the phone            // into a            // full wake lock.            if (fullWake) {                Log.d(TAG, "Need to take full wake lock");                wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, WAKE_LOCK_TAG);            } else {                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);            }            wakeLock.setReferenceCounted(false);        }        Log.d(TAG, "Acquiring wake lock");        wakeLock.acquire();    }    private void releaseWakeLock() {        Log.d(TAG, "Releasing wake lock");        if (wakeLock != null) {            wakeLock.release();            wakeLock = null;            Log.d(TAG, "Finished releasing wake lock");        } else {            Log.e(TAG, "Couldn't release null wake lock");        }    }    private void takeWifiLock() {        Log.d(TAG, "Taking wifi lock");        if (wifiLock == null) {            WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);            wifiLock = manager.createWifiLock("SwiFTP");            wifiLock.setReferenceCounted(false);        }        wifiLock.acquire();    }    private void releaseWifiLock() {        Log.d(TAG, "Releasing wifi lock");        if (wifiLock != null) {            wifiLock.release();            wifiLock = null;        }    }

開啟移動網路

//開啟或關閉GPRS       private boolean gprsEnabled(boolean bEnable)      {          Object[] argObjects = null;                            boolean isOpen = gprsIsOpenMethod("getMobileDataEnabled");          if(isOpen == !bEnable)          {              setGprsEnable("setMobileDataEnabled", bEnable);          }                    return isOpen;        }            //檢測GPRS是否開啟       private boolean gprsIsOpenMethod(String methodName)      {          Class cmClass       = mCM.getClass();          Class[] argClasses  = null;          Object[] argObject  = null;                    Boolean isOpen = false;          try          {              Method method = cmClass.getMethod(methodName, argClasses);                isOpen = (Boolean) method.invoke(mCM, argObject);          } catch (Exception e)          {              e.printStackTrace();          }            return isOpen;      }            //開啟/關閉GPRS       private void setGprsEnabled(String methodName, boolean isEnable)      {          Class cmClass       = mCM.getClass();          Class[] argClasses  = new Class[1];          argClasses[0]       = boolean.class;                    try          {              Method method = cmClass.getMethod(methodName, argClasses);              method.invoke(mCM, isEnable);          } catch (Exception e)          {              e.printStackTrace();          }      }  

AndroidManifest.xml裡添加許可權:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>

防止apk被反編譯:

// 將此函數添加到要防止被反編譯的類中即可!// 注意:1.for 迴圈不可用 do{}while(false) 的形式來代替,否則無效!//    2.a[0 - i] = 0; 數組下標必須為數值計算(0 - i)的形式,否則無效!private static void // static 最好保留以防被最佳化掉此函數AntiDecompile(){    char a[] = { 0 };    for( int i = 0;              i < 1;              i++ )    {         a[0 - i] = 0;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.