这是笔者在之前的 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; } } 复制代码
待续。。。