Android常用功能實例 如IMEI號

Android 屏幕顯示設置

程序中默的顯示是帶有標題欄和系統信息欄的,有的時候,這很影響程序界面的美觀。手機默認的是豎屏,或與感應器狀態相關,爲了某種效果,我們的程序需要限制使用橫屏或豎屏。以下的代碼就解決了上述問題。

//設置爲無標題欄

requestWindowFeature(Window.FEATURE_NO_TITLE);

//設置爲全屏模式

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

//設置爲橫屏

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


Android Intent參數傳遞

當Activity與Activity/Service(或其它情況)有時與要進行參數傳遞,最常用也是最簡單的方式就是通過Intent來處理。
看如下代碼:

Intent intent = new Intent(...);
Bundle bundle = new Bundle();
bundle.putString("NAME", "zixuan");
intent.putExtras(bundle);
context.startActivity(intent); 或 context.startService(intent);


當然,有傳送就有接收,接收也很簡單,如:

Bundle bunde = intent.getExtras();
String name = bunde.getInt("NAME");

當然參數KEY要與傳送時的參數一致。

Android 獲取手機號/手機串號

在j2me中,根本沒有辦法獲取用戶的手機號碼,就連獲取手機串號(IMEI)都基本上無法實現,然後在android手機上一切都是如此的簡單,看代碼:

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
String tel = tm.getLine1Number();

看來,android的確加速了j2me的消亡。

Android 振動器

總感覺手機上的振動器沒有多大用處(當然靜音模式下的振鈴很有用),但還是順帶着說一下吧,只有兩行代碼:
1、獲取振動服務的實例
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
2、設置振動時長,單位當然也是ms
vibrator.vibrate(1000);
如果你覺得這樣過去單調的話,可以設個節奏:
vibrator.vibrate(new long[]{10, 100, 20, 200}, -1);
兩個參數,習慣告訴我第一個是節奏,第二個是重複次數,可事實並沒有這麼簡單,我翻譯不好,大家還是看原文吧:

public void vibrate (long[] pattern, int repeat)
pattern: an array of longs of times to turn the vibrator on or off.
repeat: the index into pattern at which to repeat, or -1 if you don't want to repeat.

google喜歡弄些技巧,我卻覺得這裏有點弄巧成拙了。

Android 鬧鐘

最近看了一下Android的鬧鐘管理類(AlarmManager),真不錯誤,強大又簡單,代碼如下:

1、建立一個AlarmReceiver繼承入BroadcastReceiver,並在AndroidManifest.xml聲明

public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "鬧鐘提示:時間到!", Toast.LENGTH_LONG).show();
}
}

2、建立Intent和PendingIntent,來調用目標組件。

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

3、設置鬧鐘
獲取鬧鐘管理的實例:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

設置單次鬧鐘:

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5*1000), pendingIntent);

設置週期鬧鐘:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10*1000), (24*60*60*1000), pendingIntent);


搞定!當然這裏鬧鐘的響應處理只是用的文字,你可以播放聲音,或都用更復雜的一系統通知,在這裏你就是上帝,一切由你做主。
發佈了43 篇原創文章 · 獲贊 0 · 訪問量 2673
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章