有用的Android代码片段收集,方便自己和大家
1,采用Global变量在多个应用间共享配置数据
定义变量:
settings.java : TEST_IN_SETUP_USER_FLOW
设置变量:
Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.TEST_IN_SETUP_USER_FLOW, 1 );
获得变量:
int testIsUserFlow = Settings.Global.getInt(mTSBLauncherActivity.getContentResolver(), Settings.Global.TEST_IN_SETUP_USER_FLOW, 0);
2,实现超时操作
if(timer != null){
timer.cancel();
timer =null;
}
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
@Override
public void run()
{
// TODO Auto-generated method stub
Log.i(TAG," TimerTask time out...");
}
};
timer.schedule(task ,2*1000); //set the time
3,从桌面移除图标
PackageManager pm = getPackageManager();
ComponentName name = new ComponentName(this, Tutorial_spec.class);
pm.setComponentEnabledSetting(name,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
4,得到当前时间
1,long time = SystemClock.uptimeMillis();
2,Date curDate = new Date(System.currentTimeMillis());
3,SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
4,SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
5,String date = sDateFormat.format(new java.util.Date());
5,手机的横屏显示
XML:android:screenOrientation="landscape"//可能不会起作用
代码中:setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
6,判断当前状态栏高度
/**
* 用于获取状态栏的高度。
*
* @return 返回状态栏高度的像素值。
*/
private int getStatusBarHeight() {
if (statusBarHeight == 0) {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object o = c.newInstance();
Field field = c.getField("status_bar_height");
int x = (Integer) field.get(o);
statusBarHeight = getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
}
return statusBarHeight;
}
7,按照字符顺排序
/**
* Perform alphabetical comparison of application entry objects.
*/
public static final Comparator<AppEntry> ALPHA_COMPARATOR = new Comparator<AppEntry>() {
private final Collator sCollator = Collator.getInstance();
@Override
public int compare(AppEntry object1, AppEntry object2) {
return sCollator.compare(object1.getLabel(), object2.getLabel());
}
};
调用排序
// Sort the list.
Collections.sort(entries, ALPHA_COMPARATOR);