Android的getSystemService总结和具体使用方法

根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。
 
           传入的Name           |           返回的对象              |         说明
  • 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 { 

 

 

 

 

 


 

        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); 

 

 

 

 

 

  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 

 

 

 

 

 

        // 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         }); 

 

 

 

 

 

        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) { 

 

 

---------

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);

}

 

posted @ 2015-04-06 14:33  壮汉请留步  阅读(4192)  评论(0编辑  收藏  举报