- WINDOW_SERVICE WindowManager 管理打開的窗口程序
- LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定義的view
- ACTIVITY_SERVICE ActivityManager 管理應用程序的系統狀態
- POWER_SERVICE PowerManger 電源的服務
- ALARM_SERVICE AlarmManager 鬧鍾的服務
- NOTIFICATION_SERVICE NotificationManager 狀態欄的服務
- KEYGUARD_SERVICE KeyguardManager 鍵盤鎖的服務
- LOCATION_SERVICE LocationManager 位置的服務,如GPS
- SEARCH_SERVICE SearchManager 搜索的服務
- VEBRATOR_SERVICE Vebrator 手機震動的服務
- CONNECTIVITY_SERVICE Connectivity 網絡連接的服務
- WIFI_SERVICE WifiManager Wi-Fi服務
- TELEPHONY_SERVICE TeleponyManager 電話服務
函數getSystemService。
public Object getSystemService (String name) Parameters
name The name of the desired service.
Returns The service or null if the name does not exist.
Open Declaration Object android.app.Activity.getSystemService(String name)
Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:
Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)
譯文:通過這個接口獲取到的System services(系統服務)會和他們相應的Context(上下文)有緊密聯系。通常,不要在不同的上下文中(Activities, Applications, Services, Providers,etc.)共享同一個System services對象。
---------》WINDOW_SERVICE ("window")
The top-level window manager in which you can place custom windows. The returned object is a WindowManager. 使用方法,例如:
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getContext().getSystemService( Context.WINDOW_SERVICE); Display d = wm.getDefaultDisplay(); d.getMetrics(metrics);
addResult(SCREEN_WIDTH, metrics.widthPixels); addResult(SCREEN_HEIGHT, metrics.heightPixels); addResult(SCREEN_DENSITY, metrics.density); addResult(SCREEN_X_DENSITY, metrics.xdpi); addResult(SCREEN_Y_DENSITY, metrics.ydpi); 注意addResult是自定義函數。
其中DisplayMetrics還可以這樣使用,
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics); 重點需要關注WindowManager的getDefaultDisplay用法。
---------》LAYOUT_INFLATER_SERVICE ("layout_inflater") A LayoutInflater for inflating layout resources in this context. 例如:
final LayoutInflater mInflater;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); public View getView(int position, View convertView, ViewGroup parent) { View view;
if (convertView == null) { view = mInflater.inflate(
android.R.layout.simple_list_item_1, parent, false); } else {
2
view = convertView; }
bindView(view, mList.get(position)); return view; }
注意其中的inflate方法。
---------》ACTIVITY_SERVICE ("activity")
A ActivityManager for interacting with the global activity state of the system. 使用方法,例如:
public AppListAdapter(Context context) { mContext = context;
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo app : appList) { if(mList == null) {
mList = new ArrayList<ListItem>(); }
mList.add(new ListItem(app)); }
if (mList != null) {
Collections.sort(mList, sDisplayNameComparator); } }
注意getRunningAppProcesses()方法。
---------》POWER_SERVICE ("power")
A PowerManager for controlling power management. 例如:
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); pm.goToSleep(SystemClock.uptimeMillis()); 注意goToSleep()方法。 再如:
private WakeLock mWakeLock = null;
mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ConnectivityTest"); mWakeLock.acquire(); (mWakeLock.release();)
---------》ALARM_SERVICE ("alarm")
A AlarmManager for receiving intents at the time of your choosing. 例如: 設置鬧鍾
private void scheduleAlarm(long delayMs, String eventType) { AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(CONNECTIVITY_TEST_ALARM);
3
i.putExtra(TEST_ALARM_EXTRA, eventType); i.putExtra(TEST_ALARM_ON_EXTRA, Long.toString(mSCOnDuration)); i.putExtra(TEST_ALARM_OFF_EXTRA, Long.toString(mSCOffDuration)); i.putExtra(TEST_ALARM_CYCLE_EXTRA, Integer.toString(mSCCycleCount)); PendingIntent p = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayMs, p); }
---------》NOTIFICATION_SERVICE ("notification")
A NotificationManager for informing the user of background events. 用於顯示通知欄,例如如下經典函數: protected void showNotification() {
// look up the notification manager service //創建NotificationManager
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// The details of our fake message //顯示的信息,title和content CharSequence from = "Joe";
CharSequence message = "kthx. meet u for dinner. cul8r";
// The PendingIntent to launch our activity if the user selects this notification //點擊事件的相應窗口
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, IncomingMessageView.class), 0);
// The ticker text, this uses a formatted string so our message could be localized String tickerText = getString(R.string.imcoming_message_ticker_text, message);
// construct the Notification object.
Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis());
// Set the info for the views that show in the notification panel. notif.setLatestEventInfo(this, from, message, contentIntent);
// after a 100ms delay, vibrate for 250ms, pause for 100 ms and // then vibrate for 500ms.
notif.vibrate = new long[] { 100, 250, 100, 500};
// Note that we use R.layout.incoming_message_panel as the ID for // the notification. It could be any integer you want, but we use // the convention of using a resource id for a string related to
// the notification. It will always be a unique number within your
4
// application.
nm.notify(R.string.imcoming_message_ticker_text, notif); }
---------》KEYGUARD_SERVICE ("keyguard") A KeyguardManager for controlling keyguard.
鍵盤鎖,例如:
KeyguardManager keyguardManager =
(KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if (keyguardManager.inKeyguardRestrictedInputMode()) { return false; }
---------》LOCATION_SERVICE ("location")
A LocationManager for controlling location (e.g., GPS) updates. 得到位置信息,例如:
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); Location location = null;
List<String> providers = locationManager.getAllProviders(); for (int i = 0; i < providers.size(); ++i) { String provider = providers.get(i);
location = (provider != null) ? locationManager.getLastKnownLocation(provider) : null; if (location != null) break; }
---------》SEARCH_SERVICE ("search") A SearchManager for handling search. 創建搜索服務,例如:
SearchManager searchManager =
(SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
ComponentName name = searchManager.getWebSearchActivity(); if (name == null) return null;
SearchableInfo searchable = searchManager.getSearchableInfo(name); if (searchable == null) return null;
---------》VIBRATOR_SERVICE ("vibrator")
A Vibrator for interacting with the vibrator hardware. 提供震動服務,例如:
private static final SparseArray<long[]> sVibrationPatterns = new SparseArray<long[]>(); static {
sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_CLICKED, new long[] { 0L, 100L });
5
sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED, new long[] { 0L, 100L });
sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_SELECTED, new long[] { 0L, 15L, 10L, 15L });
sVibrationPatterns.put(AccessibilityEvent.TYPE_VIEW_FOCUSED, new long[] { 0L, 15L, 10L, 15L });
sVibrationPatterns.put(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, new long[] { 0L, 25L, 50L, 25L, 50L, 25L });
sVibrationPatterns.put(INDEX_SCREEN_ON, new long[] { 0L, 10L, 10L, 20L, 20L, 30L });
sVibrationPatterns.put(INDEX_SCREEN_OFF, new long[] { 0L, 30L, 20L, 20L, 10L, 10L }); }
private Vibrator mVibrator;
mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
Handler mHandler = new Handler() { @Override
public void handleMessage(Message message) { switch (message.what) {
case MESSAGE_VIBRATE: int key = message.arg1;
long[] pattern = sVibrationPatterns.get(key); mVibrator.vibrate(pattern, -1); return;
case MESSAGE_STOP_VIBRATE: mVibrator.cancel(); return; } } };
---------》CONNECTIVITY_SERVICE ("connection")
A ConnectivityManager for handling management of network connections. 得到網絡連接的信息,例如:
private boolean isNetworkConnected() {
NetworkInfo networkInfo = getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected(); }
private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connectivity =
(ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return null;
}
return connectivity.getActiveNetworkInfo();
}
---------
》
WIFI_SERVICE ("wifi")
A WifiManager for management of Wi-Fi connectivity.
例如:
進行
wifi
的打開,關閉,狀態判斷等。
private WifiManager mWm;
mWm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
創建兩個
View
單擊事件的監聽器,監聽器實現
onClick()
方法:
private View.OnClickListener mEnableWifiClicked = new View.OnClickListener() {
public void onClick(View v) {
mWm.setWifiEnabled(true);
}
};
private View.OnClickListener mDisableWifiClicked = new View.OnClickListener() {
public void onClick(View v) {
mWm.setWifiEnabled(false);
}
};
---------
》
INPUT_METHOD_SERVICE ("input_method")
An InputMethodManager for management of input methods.
得到鍵盤或設置鍵盤相關信息,例如:
private void hideSoftKeyboard() {
// Hide soft keyboard, if visible
InputMethodManager inputMethodManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mList.getWindowToken(), 0);
}
---------
》
UI_MODE_SERVICE ("uimode")
An UiModeManager for controlling UI modes.
UI
信息相關,例如:
int mUiMode = Configuration.UI_MODE_TYPE_NORMAL;
try {
IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
ServiceManager.getService(Context.UI_MODE_SERVICE));
mUiMode = uiModeService.getCurrentModeType();
} catch (RemoteException e) {
}
7
---------
》
DOWNLOAD_SERVICE ("download")
A DownloadManager for requesting HTTP downloads
下載相關的接口,例如:
private void downloadUpdate(Context context, String downloadUrl, String fileName) {
LogUtil.i(TAG
, "downloadUpdate downloadUrl = " + downloadUrl);
Uri downloadUri = Uri.parse(downloadUrl);
DownloadManager dm = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
Request downloadRequest = new Request(downloadUri);
//downloadRequest.setDescription(context.getText(R.string.upd_auto_check_prompt));
downloadRequest.setVisibleInDownloadsUi(true); //TODO:change to false when release!
//downloadRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI);
downloadRequest.setDestinationInExternalPublicDir("DoctorAn", fileName);
downloadRequest.setTitle(context.getString(R.string.upd_downloading));
long downloadId = dm.enqueue(downloadRequest);
Map<String, String> temp = new HashMap<String, String>();
temp.put("fileName", fileName);
((MPApplication)context.getApplicationContext()).getDownloadMap().put(downloadId, temp);
