本文共 4098 字,大约阅读时间需要 13 分钟。
2018年的春节余韵尚未消散,阿里巴巴为移动开发者们准备了一份迟到的新年礼物——《阿里巴巴Android开发手册》1.0.1版本。在此,撰写阅读笔记,记录作为开发者的一些注意事项,规范自身编码习惯。
作为开发者,在日常开发中可能会遇到各种问题,以下是阿里巴巴手册中的一些重要推荐:
避免在发出Intent之前未调用resolveActivity检查,这可能导致系统找不到合适的Activity组件,进而抛出错误。示例代码如下:
public void viewUrl(String url, String mimeType) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), mimeType); if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) { startActivity(intent); } else { // 处理找不到Activity的情况 }}
由于onReceive方法在主线程执行,耗时操作会导致UI不流畅。推荐方法有:使用IntentService、创建HandlerThread或在其他线程中注册BroadcastReceiver。
FragmentTransaction.commit()如果在Activity保存状态之后调用,可能导致页面恢复时无法还原状态,因而引发 IllegalStateExceptionStateLoss异常。推荐在onPostResume或onResumeFragments中调用commit()。
对于仅用于应用内的广播,建议使用LocalBroadcastManager避免广播泄漏或被拦截,同时提高效率。
使用dp而非sp,虽然sp长时有早期推荐,但dp更具一致性,避免因系统设置影响UI。
例如:Environment.getExternalStorageDirectory()、getExternalStoragePublicDirectory()、Context#getFilesDir()、Context#getCacheDir()。
避免造成安全风险,如文件权限泄漏。
正确做法是使用参数化方式,避免SQL注入。
示例代码如下:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options);}
示例代码如下:
public class MyActivity extends Activity { ImageView mImageView; Animation mAnimation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageView = (ImageView) findViewById(R.id.ImageView01); mAnimation = AnimationUtils.loadAnimation(this, R.anim.anim); mBtn = (Button) findViewById(R.id.Button01); mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mImageView.startAnimation(mAnimation); } }); } @Override public void onPause() { mImageView.clearAnimation(); }}
示例代码如下:
View v = findViewById(R.id.xxxViewID);final FadeUpAnimation anim = new FadeUpAnimation(v);anim.setInterpolator(new AccelerateInterpolator());anim.setDuration(1000);anim.setFillAfter(true);new Handler().postDelayed(new Runnable() { public void run() { if (v != null) { v.clearAnimation(); } }}, anim.getDuration());v.startAnimation(anim);
以上内容为手册中的一些重要推荐,其实内容虽多,但1.0.1版本后还将继续完善。每一点细节都体现出对开发的深思熟虑,希望能为大家的开发工作带来一些启发。
转载地址:http://hjyrz.baihongyu.com/