關鍵字:網絡狀態,系統設置,系統時間,時間格式化
首先是判斷系統的網絡狀態
/**
* 對網絡連接狀態進行判斷
* @return true, 可用; false, 不可用
*/
private boolean isOpenNetwork() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
PS:你肯定要加入網絡訪問的權限
[html]
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
如果沒有網絡則進入設置界面
[java]
if (isOpenNetwork() == true) {
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
SomeActivity.this);
builder.setTitle("title")
.setMessage("message");
builder.setPositiveButton(resources.getString(R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
<span style="white-space:pre"> </span>Intent intent = null;
try {
String sdkVersion = android.os.Build.VERSION.SDK;
if (Integer.valueOf(sdkVersion) > 10) {
intent = new Intent(
android.provider.Settings.ACTION_SETTINGS);
} else {
intent = new Intent();
ComponentName comp = new ComponentName(
"com.android.settings",
"com.android.settings.Settings");
intent.setComponent(comp);
intent.setAction("android.intent.action.VIEW");
}
SomeActivity.this.startActivity(intent);
} catch (Exception e) {
Log.v("LOG","open network settings failed, please check...");
<span style="white-space:pre"> </span>e.printStackTrace();
<span style="white-space:pre"> </span>}
}
})
.setNegativeButton(resources.getString(R.string.no),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
finish();
}
}).show();
}
這裡再引申一下,通過android.provider.Settings可以獲取很多我們需要的和系統設置相關的信息,比如系統時間是24還是12制
[java]
ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
if(strTimeFormat.equals("24"))
{
Log.i("activity","24");
}
額。。這篇博客寫得比較雜,那就把時間格式化,獲取系統時間也補上吧
[java]
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM"); //參數為你想要顯示的時間格式
String date=sdf.format(new java.util.Date());
利用Calendar獲取
[java]
Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
month = c.grt(Calendar.MONTH)
day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE)
Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
month = c.grt(Calendar.MONTH)
day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE)
利用Time獲取
[java]
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone資料。
t.setToNow(); // 取得系統時間。
int year = t.year;
int month = t.month;
int date = t.monthDay;
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;