1.Activity间通过Intent的跳转,必须先通过resolveActivity
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)
{
try{
startActivity(intent);
}catch(ActivityNotFoundException e){
}
}
}
2.避免在BroadcastReceiver#onReceive()中执行耗时操作,
如果有耗时工作,应该创建IntentService完成;
3.避免Intent应用内传递敏感信息,可以使用LocalBroadcaseManager#sendBroadcast()
实现
Intent intent=new Intent("my-sensitive-event");
intent.putExtra("event","this is a test event");
LocalBroadcaseManager.getInstance(this).sendBroadcast(Intent);
4.Activity#onPostResume()或者FragmentActivity#onResumeFragments()
内调用FragmentTransaction#commit();
5.推荐在Activity#onPause()/onStop()中结合isFinishing 的判断执行
释放资源的工作;
@Override
protected void onStop() {
super.onStop();
if(isFinishing()) {
}
}
6.不要在Activity#onPause方法做耗时操作,此方法执行后会进入下一个Activity
的onCreat方法;
7.在Adapter的时候,都需要设置TextView的setText(""); 否则由于
Adapter item的复用原因,会显示错乱;
8.避免UI多层嵌套,页面拥有的View越多,measure、layout、draw所花费的时间
就越久;不要使用LinearLayout嵌套,改用RelativityLayout;
9.在Activity中显示对话框或者弹出浮层时,尽量使用DialogFragment
,而非Dialog/AlertDialog,可以跟随Activity的生命周期管理对话框/弹出浮层
的生命周期
public void showPromptDialog(String text){
DialogFragment promptDialog=new DialogFragment(){
@Override
public View onCreateView(LayoutInflater inflarer,ViewGroup container,
Bundle saveInstanceState)
{
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View view=inflater.inflate(R.layout.jjj);
return view;
}
}
promptDialog.show(getFragmentManager(),text);
}
10.禁止在ScrollView内嵌套ListView/GridView/ExpandableListView/RecyclerView,
对性能有较大的耗损,推荐使用android.support.v4.widget.NestedScrollView
11.新建线程时,必须通过线程池提供(AsyncTask或者ThreadPoolExecutor)
不允许在应用中自行创建线程,如果不适用线程池,可能会造成系统创建大量同类线程而
导致消耗完内存或者“过度切换”的问题;
int NUMBER_OF_CORES=Runtime.getRuntime().availableProcessors();
int KEEP_ALIVE_TIME=1;
TimeUnit KEEP_ALIVE_TIME_UNIT=TimeUnit.SECONDS;
BlockingQueue<Runnable> taskQueue=new LinkedBlockingQueue<Runnable>();
ExecutorService executorService =new ThreadPoolExecutor(
NUMBER_OF_CORES,
NUMBER_OF_CORES*2,
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
taskQueue,
new BackgroundThreadFactory(),
new DefaultRejectedExecutionHandler());
executorService.execute(new Runnable(){
#Override
public void run(){
}
});
12.推荐ThreadPoolExecutor设置线程存活时间setKeepAliveTime,确保空闲时
线程能被释放;
13.读写文件使用Android的API访问:
Environment#getExternalStorageDirectory();
Environment#getExternalStoragePublicDirectory();
Context#getFilesDir();
Context#getCacheDir();
14.SharedPreference提交数据时,尽量使用Editor#apply(),
apply方法进行提交会写入内存,然后异步写入磁盘,commit方法是
直接写入磁盘,如果频繁操作的话apply的性能会优于commit;
如果想立即获取存储操作的结果,应当使用commit.
15.png使用tinypng,减少包面积;
16.工具类,包名为单数,类名为复数;
17.Long或long定义的变量以L结尾;
18.小括号和字符直接不需要空格;
19.单行字符不得超过120个