Android 開發功能模組總結

hogen發表於2018-01-02

還是來了

這是筆者在之前的 Android 開發中遇到的一些常用的模組化寫法,用的還是比較多的,在這裡記錄一下!其實這些程式碼不需要去記,實在不記得了查一下就 OK 了!

獲取app的版本號

private int getVersionCode() {
	PackageManager packageManager = getPackageManager();
	try {
		PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
		int versionCode = packageInfo.versionCode;
		return versionCode;
	} catch (NameNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return -1;
}
複製程式碼

獲取app的版本名稱

private String getVersionName() {
	PackageManager packageManager = getPackageManager();
	try {
		PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
		String versionName = packageInfo.versionName;
		return versionName;
	} catch (NameNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return "";
}
複製程式碼

判斷sd卡是否掛載

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
	//如果有,則目標路徑為....
	String target = Environment.getExternalStorageDirectory()+"update.apk";
}else {
	Toast.makeText(SplashActivity.this, "sd卡不存在,親!", Toast.LENGTH_SHORT).show();
}
複製程式碼

跳轉到系統下載介面

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.fromFile(arg0.result),"application/vnd.android.package-archive");
startActivity(intent);
複製程式碼

判斷出當前是否有網路

//首先通過 getSystemService()方法得到了 ConnectivityManager 的例項, 這是一個系統服務類, 專門用於管理網路連線
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
	Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
} else {
	Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
}
複製程式碼

簡訊接收

// 如果是接收到簡訊
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
	// 取消廣播(這行程式碼將會讓系統收不到簡訊)
	abortBroadcast(); // 
	StringBuilder sb = new StringBuilder();
	// 接收由SMS傳過來的資料
	Bundle bundle = intent.getExtras();
	// 判斷是否有資料
	if (bundle != null) {
		// 通過pdus可以獲得接收到的所有簡訊訊息
		Object[] pdus = (Object[]) bundle.get("pdus");
		// 構建簡訊物件array,並依據收到的物件長度來建立array的大小
		SmsMessage[] messages = new SmsMessage[pdus.length];
		for (int i = 0; i < pdus.length; i++) {
			messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
		}
		// 將傳送來的簡訊合併自定義資訊於StringBuilder當中
		for (SmsMessage message : messages) {
			sb.append("簡訊來源:");
			// 獲得接收簡訊的電話號碼
			sb.append(message.getDisplayOriginatingAddress());
			sb.append("\n------簡訊內容------\n");
			// 獲得簡訊的內容
			sb.append(message.getDisplayMessageBody());
		}
	}
	Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
}
複製程式碼

清單檔案

<receiver android:name="com.lhg.smsintercept.SmsReceiver" >
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
複製程式碼

監聽SD卡

//判斷收到的到底是什麼廣播
String action = intent.getAction();
if(Intent.ACTION_MEDIA_MOUNTED.equals(action)){
	Toast.makeText(context, "SD卡可用", 0).show();
}else if(Intent.ACTION_MEDIA_UNMOUNTED.equals(action)){
	Toast.makeText(context, "sd不可用", 0).show();
}else if(Intent.ACTION_MEDIA_REMOVED.equals(action)){
	Toast.makeText(context, "sd卡已拔出	", 0).show();
}
複製程式碼

清單檔案

 <receiver android:name="com.lhg.sdlistener.SDStatusListener">
    <intent-filter >
        <action android:name="android.intent.action.MEDIA_MOUNTED"/>
        <action android:name="android.intent.action.MEDIA_REMOVED"/>
        <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
        <data android:scheme="file"/>
    </intent-filter>
 </receiver>
複製程式碼

獲取電池狀態

@Override
public void onReceive(Context context, Intent intent) {
	// 獲取當前電池狀態資訊
	String action = intent.getAction();
	if (Intent.ACTION_BATTERY_LOW.equals(action)) {
		tv_battery.setText("電池電量不足,快他媽充電去...");
	}else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
		// (1)取得當前電量
		Bundle bundle = intent.getExtras();
		int currentLevel = bundle.getInt("level");
		// (2)取得總電量
		int total = bundle.getInt("scale");
		// (3)顯示
		double persent = currentLevel * 100 / total;
		tv_battery.setText("當前電量為:" + persent + "%");
	}else if (Intent.ACTION_BATTERY_OKAY.equals(action)) {
		tv_battery.setText("電池充好了,快他媽起來嗨...");
	}
}
複製程式碼

##監控應用程式的狀態 @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); Uri uri = intent.getData(); if(Intent.ACTION_PACKAGE_ADDED.equals(action)){ Toast.makeText(context,uri.toString()+"被安裝了", 0).show(); }else if(Intent.ACTION_PACKAGE_REPLACED.equals(action)){ Toast.makeText(context,uri.toString()+"被升級了", 0).show(); }else if(Intent.ACTION_PACKAGE_REMOVED.equals(action)){ Toast.makeText(context,uri.toString()+"被解除安裝了", 0).show(); } } 清單檔案

<receiver android:name="com.lhg.packagelistener.AppStateReceiver">
    <intent-filter >
        <action android:name="android.intent.action.PACKAGE_ADDED"/>
        <action android:name="android.intent.action.PACKAGE_REPLACED"/>
        <action android:name="android.intent.action.PACKAGE_REMOVED"/>
        <data android:scheme="package"/>
    </intent-filter>
</receiver>
複製程式碼

ListView 自定義 Adapter 寫法

class FruitAdapter extends BaseAdapter {
	private List<String> mData;
	private LayoutInflater mInflater;
	private Context mContext;
	
	public FruitAdapater(Context context, List<String> mData){
		this.mData = mData;
		mContext = context;
		//以下方式二選一
		mInflater = LayoutInflater.from(context);
		mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if(convertView == null){
			viewHolder = new ViewHolder();
			convertView =mInflater.inflate(ThirdActivity.this, R.layout.fruit_item, null);
			viewHolder.fruitImageId = (ImageView) convertView.findViewById(R.id.iv_photo);
			viewHolder.fruitName = (TextView) convertView.findViewById(R.id.tv_name);
			convertView.setTag(viewHolder);
		}else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		viewHolder.fruitImageId.setImageResource(mData.get(position).getImgId());
		viewHolder.fruitName.setText(mData.get(position).getName());
		
		return convertView;
	}
	class ViewHolder{
		ImageView fruitImageId;
		TextView fruitName;
	}
}
複製程式碼

在對話方塊中載入佈局(方式一)

	AlertDialog.Builder builder = new Builder(this);
	final AlertDialog dialog = builder.create();
	// 裝載佈局
	View dialog_view = getLayoutInflater().inflate(R.layout.add_black_number, null);
	// View dialog_view =LayoutInflater.from(this).inflate(R.layout.add_black_number, null);
	// View dialog_view = View.inflate(this, R.layout.add_black_number,null);
	//初始化控制元件
	Button bt_ok = (Button) dialog_view.findViewById(R.id.bt_ok);
	Button bt_cancle = (Button) dialog_view.findViewById(R.id.bt_cancel);
	//點選確定按鈕
	bt_ok.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			//do something....
			dialog.dismiss();
		}
	});
	// 單擊取消按鈕
	bt_cancle.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			dialog.dismiss();
		}
	});
	// 讓佈局顯示在對話方塊中
	dialog.setView(dialog_view, 0, 0, 0, 0);
	dialog.show();
複製程式碼

在對話方塊中載入佈局(方式二)

final AlertDialog dialog = new AlertDialog.Builder(this).create();
	dialog.show();//不能放在最後寫,否則會報錯
	Window window = dialog.getWindow();//拿到對話方塊所在的視窗物件
	window.setGravity(Gravity.BOTTOM);//對齊底部
	window.setContentView(R.layout.dialog);//給對話方塊設定佈局
	Button cancelBtn = (Button) window.findViewById(R.id.camera_cancel);//或用dialog.findViewById
	cancelBtn.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
			dialog.cancel();
		}
	});
=============================使對話方塊與螢幕寬度持平=============================================
    final  Dialog dialog = new Dialog(this,R.style.BottomDialog);
    dialog.show();
    dialog.setContentView(R.layout.dialog);
    dialog.setCanceledOnTouchOutside(true);// 外部點選取消
    Button btnCancel = (Button) dialog.findViewById(R.id.btn_cancel);
   
    Window window = dialog.getWindow();
    window.setWindowAnimations(R.style.AnimDialog);//對話方塊進出螢幕的動畫
    //使對話方塊寬度與手機寬度持平
    WindowManager.LayoutParams params = window.getAttributes();
    params.gravity = Gravity.BOTTOM;
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    //params.height = getWindowManager().getDefaultDisplay().getHeight()*3/5;
    window.setAttributes(params);
===============================AnimDialog樣式===============================================
<style name="AnimDialog" parent="@android:style/Animation">
    <item name="android:windowEnterAnimation">@anim/push_bottom_in</item>
    <item name="android:windowExitAnimation">@anim/push_bottom_out</item>
</style>

===============================BottomDialog樣式=============================================
<style name="BottomDialog" parent="@style/AppTheme">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>
===============================push_bottom_in=============================================
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="500"
        android:fromYDelta="100%p"
        android:toYDelta="0"
     />      
</set>
===============================push_bottom_out=============================================
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="500"
        android:fromYDelta="0"
        android:toYDelta="100%p" />
</set>
==============================dialog.xml====================================================
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="#D3D3D3"
    android:orientation="vertical"
    android:padding="15dp" >

    <Button
        android:id="@+id/camera_camera"
        android:layout_width="320dp"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:text="直接拍照上傳"
        android:textSize="18sp" />

    <Button
        android:id="@+id/camera_phone"
        android:layout_width="320dp"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:text="從手機相片選擇"
        android:textSize="18sp" />

    <Button
        android:id="@+id/camera_cancel"
        android:layout_width="320dp"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:text="取消"
        android:textColor="#ff77ff"
        android:textSize="18sp" />

</LinearLayout>
複製程式碼

自定義控制元件樣式

<style name="TitleSytle">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">50dp</item>
    <item name="android:background">#8866ff00</item>
    <item name="android:gravity">center</item>
    <item name="android:textColor">@color/black</item>
    <item name="android:textSize">22sp</item>
</style>
複製程式碼

Android 進行單元測試步驟

  • 在清單檔案中說明,與 Application 同級

       <instrumentation
          android:name="android.test.InstrumentationTestRunner"
          android:targetPackage="com.excel.androidtestcase" >
      </instrumentation>
    複製程式碼
  • 增加測試庫,與 activity 同級

      <uses-library android:name="android.test.runner"/>
    複製程式碼
  • 繼承自 ActivityTestCase

      public class MainActivity extends ActivityTestCase {
      	public void test1() {
      		int result = Utils.add(2, 5);
      		// 斷言:用來檢測實際值與期望值是否一致
      		assertEquals(7, result);
      	}
      	public void test2(){
      		 Utils.divide(2, 4);
      	}
      }
    複製程式碼
  • Utils 類說明

      public class Utils {
      	public static int add(int i, int j){
      		return i + j;
      	}			
      	public static void divide(int i, int j){
      		int result = i / j;
      	}
      }
    複製程式碼

待續。。。

相關文章