Android 关于系统Context.getSystemService(String arg0)获取系统服务的详细剖析-getSystemService

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jspping/article/details/51452403


前段时间在写系统 launcher 的时候,客户需要引入一个天气模块,起初我只是用了一个百度的车联网的天气api,发现调用次数有限制,并且很多家客户觉得

这个天气模块效果还挺不错的,都想在自己的产品上加上我这个模块,我就想了想该怎么坐,满足所有的需求,并且也方便其他同时引用我这个模块,我就花

了一下午的时间,在网上爬了一个javascript的接口,然后在自己的网站服务器上再多做了一个动态代理,相当于我本地请求到我自己的网站服务器,我的服务

器在做一次转发请求拿到数据,本地设备端通过这个动态代理获取天气数据,此数据没有任何限制,不限制ip,不限制次数,相当实用,解决了API的问题,接

下来需要解决引用的问题,就是代码的复用性和灵活性,这时候我就想了一个比较简便的方法,就是自己封装一个jar包,在任何应用里面或者web里面都可以

引用它,因为只更新到了 1.0 版本,暂时只支持 android 端,后续可能会更新到兼容其他平台,然后关于jar的调用也非常的简单实用,测试之后感觉非常不

错,而且也非常小,调用端不用考虑定位和网络问题,下面奉上demo,关于系统Context.getSystemService(String 

arg0),后面会抛砖引玉带出来,给大家讲。


我封装的jar包:



jar 构架:



demo 调用:

package com.example.rmt.weather.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import rmt.weather.core.WeatherInfo;
import rmt.weather.core.util.WeatherInfoCallBack;
import rmt.weather.core.util.WeatherManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements WeatherInfoCallBack{

	private TextView release,getWeather,reset_init,net_message,gps_message,weather_message,
	count_message;
	
	private String net_status,gps_status,weather_status,date_status;
	private int count = 0;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==0){
				net_message.setText(net_status);
				gps_message.setText(gps_status);
				weather_message.setText(weather_status);
				count_message.setText("第"+count+"次更新天气信息\r\r\r\r"+date_status);
			}else{
				net_message.setText("");
				gps_message.setText("");
				weather_message.setText("");
				count_message.setText("");
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initWeatherManager();
		initView();
	}
	
	/**
	 * jar:需要注册的权限
	 * <uses-permission android:name="android.permission.INTERNET" />
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	 * */
	
	/**
	 * jar:需要注册的组件
	 * <receiver android:name="rmt.weather.core.WeatherUpdateReceiver"/>
     * <service  android:name="rmt.weather.core.WeatherService"/>
	 * */
	
	private void initView(){
		release = (TextView) findViewById(R.id.release);
		getWeather = (TextView) findViewById(R.id.get_weather);
		reset_init  = (TextView) findViewById(R.id.reset_init);
		net_message = (TextView) findViewById(R.id.net_message);
		gps_message = (TextView) findViewById(R.id.gps_message);
		weather_message = (TextView) findViewById(R.id.weather_message);
		count_message = (TextView) findViewById(R.id.count_message);
		
		release.setOnClickListener(listener);
		getWeather.setOnClickListener(listener);
		reset_init.setOnClickListener(listener);
	}
	
	/**
	 * initWeatherManager()
	 * 初始化天气管理服务
	 * 用于初次初始化应用,调用一次
	 * */
	private void initWeatherManager(){
		WeatherManager.getWeatherManager().init(this);
		WeatherManager.getWeatherManager().setWeatherInfoCallBack(this);
	}
	
	/**
	 * resetWeather()
	 * 重新初始化天气管理服务
	 * 用于休眠结束之后再次开机
	 * */
	private void resetWeather(){
		initWeatherManager();
	}
	
	/**
	 * releaseAll()
	 * 释放所有内存
	 * 用于休眠前调用,调用一次
	 * */
	private void releaseAll(){
		count = 0;
		WeatherManager.getWeatherManager().releaseAll();
		mHandler.sendEmptyMessage(1);
	}
	
	/**
	 * getWeatherInfo()
	 * 获取当前的天
	 * 跨定时服务即时获取天气信息
	 * */
	private void getWeatherInfo(){
		WeatherManager.getWeatherManager().getWeatherInfo();
	}
	
	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			if(arg0.getId()==R.id.release){
				// 释放
				releaseAll();
			}else if(arg0.getId()==R.id.get_weather){
				// 即时获取当前城市天气
				getWeatherInfo();
			}else{
				// 重新初始化管理
				resetWeather();
			}
		}
	};

	private String getTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		return sdf.format(new Date(System.currentTimeMillis()));
	}

	private String getWeek() {
		SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
		return sdf.format(new Date(System.currentTimeMillis()));
	}

	private String getDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(System.currentTimeMillis()));
	}
	
	private String getDateString(){
		return getDate()+" "+getTime()+" "+getWeek();
	}
	
	/**
	 * WeatherInfoCallBack- CallBackWeatherInfo(WeatherInfo arg0)
	 * 天气信息数据回调
	 * */
	@Override
	public void CallBackWeatherInfo(WeatherInfo arg0) {
		String b = "天气信息 >>>>>> ";
		date_status = getDateString();
		weather_status = b+arg0.toString();
		count++;
		mHandler.sendEmptyMessage(0);
	}

	/**
	 *  WeatherInfoCallBack- CallBackGPSInfo(boolean arg0)
	 *  GPS 定位状态回调
	 * */
	@Override
	public void CallBackGPSInfo(boolean arg0) {
		String b = "GPS定位:";
		if(arg0){
			b = b+"成功";
		}else{
			b = b+"失败";
		}
		gps_status = b;
		mHandler.sendEmptyMessage(0);
	}

	/**
	 * WeatherInfoCallBack- CallBackNetWorkInfo(boolean arg0)
	 * 网络状态回调
	 * */
	@Override
	public void CallBackNetWorkInfo(boolean arg0) {
		String b = "网络:";
		if(arg0){
			b = b+"正常";
		}else{
			b = b+"无网络";
		}
		net_status = b;
		mHandler.sendEmptyMessage(0);
	}

}

下面开始说关于系统Context.getSystemService(String arg0),在jar里面我采用了系统alarm服务,我们就以这个服务为例

    private void startAlarm(){
        manager = (AlarmManager)mContext.getSystemService( Context.ALARM_SERVICE);
        int time = 30*60*1000;
        long triggerAtTime = SystemClock.elapsedRealtime();
        Intent intent = new Intent(mContext,WeatherUpdateReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(mContext,0,intent,0);
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,time,pi);
    }


Context.getSystemService(String arg0) 函数:

     * @see #WINDOW_SERVICE
     * @see android.view.WindowManager
     * @see #LAYOUT_INFLATER_SERVICE
     * @see android.view.LayoutInflater
     * @see #ACTIVITY_SERVICE
     * @see android.app.ActivityManager
     * @see #POWER_SERVICE
     * @see android.os.PowerManager
     * @see #ALARM_SERVICE
     * @see android.app.AlarmManager
     * @see #NOTIFICATION_SERVICE
     * @see android.app.NotificationManager
     * @see #KEYGUARD_SERVICE
     * @see android.app.KeyguardManager
     * @see #LOCATION_SERVICE
     * @see android.location.LocationManager
     * @see #SEARCH_SERVICE
     * @see android.app.SearchManager
     * @see #SENSOR_SERVICE
     * @see android.hardware.SensorManager
     * @see #STORAGE_SERVICE
     * @see android.os.storage.StorageManager
     * @see #VIBRATOR_SERVICE
     * @see android.os.Vibrator
     * @see #CONNECTIVITY_SERVICE
     * @see android.net.ConnectivityManager
     * @see #WIFI_SERVICE
     * @see android.net.wifi.WifiManager
     * @see #AUDIO_SERVICE
     * @see android.media.AudioManager
     * @see #MEDIA_ROUTER_SERVICE
     * @see android.media.MediaRouter
     * @see #TELEPHONY_SERVICE
     * @see android.telephony.TelephonyManager
     * @see #TELEPHONY_SUBSCRIPTION_SERVICE
     * @see android.telephony.SubscriptionManager
     * @see #INPUT_METHOD_SERVICE
     * @see android.view.inputmethod.InputMethodManager
     * @see #UI_MODE_SERVICE
     * @see android.app.UiModeManager
     * @see #DOWNLOAD_SERVICE
     * @see android.app.DownloadManager
     * @see #BATTERY_SERVICE
     * @see android.os.BatteryManager
     * @see #JOB_SCHEDULER_SERVICE
     * @see android.app.job.JobScheduler
     */
    public abstract Object getSystemService(@ServiceName @NonNull String name);

这个函数会由子类ContextImpl来执行,而在ContextImpl类系统服务会在这里 registerService ,所以当我们获取系统服务的时候会通过 这个类来间接得到实例

Contextimpl:

    @Override
    public Object getSystemService(String name) {
    	// 这是HashMap对象  HashMap<String, ServiceFetcher> ContextImpl.SYSTEM_SERVICE_MAP
        ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
        return fetcher == null ? null : fetcher.getService(this);
    }

Contextimpl 内部类 ServiceFetcher

 static class ServiceFetcher {
        int mContextCacheIndex = -1;

        /**
         * Main entrypoint; only override if you don't need caching.
         */
        public Object getService(ContextImpl ctx) {
            ArrayList<Object> cache = ctx.mServiceCache;
            Object service;
            synchronized (cache) {
                if (cache.size() == 0) {
                    // Initialize the cache vector on first access.
                    // At this point sNextPerContextServiceCacheIndex
                    // is the number of potential services that are
                    // cached per-Context.
                    for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
                        cache.add(null);
                    }
                } else {
                    service = cache.get(mContextCacheIndex);
                    if (service != null) {
                        return service;
                    }
                }
                service = createService(ctx);
                cache.set(mContextCacheIndex, service);
                return service;
            }
        }

        /**
         * Override this to create a new per-Context instance of the
         * service.  getService() will handle locking and caching.
         */
        public Object createService(ContextImpl ctx) {
            throw new RuntimeException("Not implemented");
        }
    }

这里得到集合里面的实例对象,其中SYSTEM_SERVICE_MAP这个系统服务集合的每个对象都来自这个函数

    private static void registerService(String serviceName, ServiceFetcher fetcher) {
        if (!(fetcher instanceof StaticServiceFetcher)) {
            fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
        }
        SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
    }
这个函数被下面这些需要注册的系统服务调用

    static {
        registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() {
                public Object getService(ContextImpl ctx) {
                    return AccessibilityManager.getInstance(ctx);
                }});

        registerService(CAPTIONING_SERVICE, new ServiceFetcher() {
                public Object getService(ContextImpl ctx) {
                    return new CaptioningManager(ctx);
                }});

        registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
                    IAccountManager service = IAccountManager.Stub.asInterface(b);
                    return new AccountManager(ctx, service);
                }});

        registerService(ACTIVITY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
                }});

        registerService(ALARM_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(ALARM_SERVICE);
                    IAlarmManager service = IAlarmManager.Stub.asInterface(b);
                    return new AlarmManager(service, ctx);
                }});

        registerService(AUDIO_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new AudioManager(ctx);
                }});

        /// M: Add AudioProfile service @{
        if (SystemProperties.get("ro.mtk_audio_profiles").equals("1") == true
                && SystemProperties.get("ro.mtk_bsp_package").equals("1") == false) {
            registerService(AUDIO_PROFILE_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new AudioProfileManager(ctx);
                } });
        }
        /// @}

        registerService(MEDIA_ROUTER_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new MediaRouter(ctx);
                }});
        /// M: Add Mobile Service @{
        if (MobileManagerUtils.isSupported()) {
            registerService(MOBILE_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    MobileManager mobileMgr = null;
                    try {
                        IBinder b = ServiceManager.getService(MOBILE_SERVICE);
                        IMobileManagerService service = IMobileManagerService.Stub.asInterface(b);
                        mobileMgr = new MobileManager(ctx, service);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return mobileMgr;
                } });
        }
        /// @}

        registerService(BLUETOOTH_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new BluetoothManager(ctx);
                }});

        registerService(HDMI_CONTROL_SERVICE, new StaticServiceFetcher() {
                public Object createStaticService() {
                    IBinder b = ServiceManager.getService(HDMI_CONTROL_SERVICE);
                    return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b));
                }});

        registerService(CLIPBOARD_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new ClipboardManager(ctx.getOuterContext(),
                            ctx.mMainThread.getHandler());
                }});

        registerService(CONNECTIVITY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
                    return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b));
                }});

        registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() {
                public Object createStaticService() {
                    IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
                    return new CountryDetector(ICountryDetector.Stub.asInterface(b));
                }});

        registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler());
                }});

        registerService(DOWNLOAD_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName());
                }});

        registerService(BATTERY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new BatteryManager();
                }});

        registerService(NFC_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new NfcManager(ctx);
                }});

        registerService(DROPBOX_SERVICE, new StaticServiceFetcher() {
                public Object createStaticService() {
                    return createDropBoxManager();
                }});

        registerService(INPUT_SERVICE, new StaticServiceFetcher() {
                public Object createStaticService() {
                    return InputManager.getInstance();
                }});

        registerService(DISPLAY_SERVICE, new ServiceFetcher() {
                @Override
                public Object createService(ContextImpl ctx) {
                    return new DisplayManager(ctx.getOuterContext());
                }});

        registerService(INPUT_METHOD_SERVICE, new StaticServiceFetcher() {
                public Object createStaticService() {
                    return InputMethodManager.getInstance();
                }});

        registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return TextServicesManager.getInstance();
                }});

        registerService(KEYGUARD_SERVICE, new ServiceFetcher() {
                public Object getService(ContextImpl ctx) {
                    // TODO: why isn't this caching it?  It wasn't
                    // before, so I'm preserving the old behavior and
                    // using getService(), instead of createService()
                    // which would do the caching.
                    return new KeyguardManager();
                }});

        registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
                }});

        registerService(LOCATION_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(LOCATION_SERVICE);
                    return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
                }});

        registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() {
            @Override
            public Object createService(ContextImpl ctx) {
                return new NetworkPolicyManager(INetworkPolicyManager.Stub.asInterface(
                        ServiceManager.getService(NETWORK_POLICY_SERVICE)));
            }
        });

        registerService(NOTIFICATION_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    final Context outerContext = ctx.getOuterContext();
                    return new NotificationManager(
                        new ContextThemeWrapper(outerContext,
                                Resources.selectSystemTheme(0,
                                        outerContext.getApplicationInfo().targetSdkVersion,
                                        com.android.internal.R.style.Theme_Dialog,
                                        com.android.internal.R.style.Theme_Holo_Dialog,
                                        com.android.internal.R.style.Theme_DeviceDefault_Dialog,
                                        com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),
                        ctx.mMainThread.getHandler());
                }});

        registerService(NSD_SERVICE, new ServiceFetcher() {
                @Override
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(NSD_SERVICE);
                    INsdManager service = INsdManager.Stub.asInterface(b);
                    return new NsdManager(ctx.getOuterContext(), service);
                }});

        // Note: this was previously cached in a static variable, but
        // constructed using mMainThread.getHandler(), so converting
        // it to be a regular Context-cached service...
        registerService(POWER_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(POWER_SERVICE);
                    IPowerManager service = IPowerManager.Stub.asInterface(b);
                    if (service == null) {
                        Log.wtf(TAG, "Failed to get power manager service.");
                    }
                    return new PowerManager(ctx.getOuterContext(),
                            service, ctx.mMainThread.getHandler());
                }});

        registerService(SEARCH_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new SearchManager(ctx.getOuterContext(),
                            ctx.mMainThread.getHandler());
                }});

        /// M: register search engine service @{
        registerService(SEARCH_ENGINE_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new SearchEngineManager(ctx);
                } });
        /// @}
        registerService(SENSOR_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new SystemSensorManager(ctx.getOuterContext(),
                      ctx.mMainThread.getHandler().getLooper());
                }});

        registerService(STATUS_BAR_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new StatusBarManager(ctx.getOuterContext());
                }});

        registerService(STORAGE_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    try {
                        return new StorageManager(
                                ctx.getContentResolver(), ctx.mMainThread.getHandler().getLooper());
                    } catch (RemoteException rex) {
                        Log.e(TAG, "Failed to create StorageManager", rex);
                        return null;
                    }
                }});

        registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new TelephonyManager(ctx.getOuterContext());
                }});

        registerService(TELEPHONY_SUBSCRIPTION_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return new SubscriptionManager(ctx.getOuterContext());
            }});

        registerService(TELECOM_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new TelecomManager(ctx.getOuterContext());
                }});

        registerService(UI_MODE_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new UiModeManager();
                }});

        registerService(USB_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(USB_SERVICE);
                    return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
                }});

        registerService(SERIAL_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(SERIAL_SERVICE);
                    return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
                }});

        registerService(VIBRATOR_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new SystemVibrator(ctx);
                }});

        registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER);

        registerService(WIFI_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(WIFI_SERVICE);
                    IWifiManager service = IWifiManager.Stub.asInterface(b);
                    return new WifiManager(ctx.getOuterContext(), service);
                }});

        registerService(WIFI_P2P_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE);
                    IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
                    return new WifiP2pManager(service);
                }});

        registerService(WIFI_SCANNING_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(WIFI_SCANNING_SERVICE);
                IWifiScanner service = IWifiScanner.Stub.asInterface(b);
                return new WifiScanner(ctx.getOuterContext(), service);
            }});

        registerService(WIFI_RTT_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(WIFI_RTT_SERVICE);
                IRttManager service = IRttManager.Stub.asInterface(b);
                return new RttManager(ctx.getOuterContext(), service);
            }});

        registerService(ETHERNET_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    IBinder b = ServiceManager.getService(ETHERNET_SERVICE);
                    IEthernetManager service = IEthernetManager.Stub.asInterface(b);
                    return new EthernetManager(ctx.getOuterContext(), service);
                }});

        registerService(WINDOW_SERVICE, new ServiceFetcher() {
                Display mDefaultDisplay;
                public Object getService(ContextImpl ctx) {
                    Display display = ctx.mDisplay;
                    if (display == null) {
                        if (mDefaultDisplay == null) {
                            DisplayManager dm = (DisplayManager)ctx.getOuterContext().
                                    getSystemService(Context.DISPLAY_SERVICE);
                            mDefaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
                        }
                        display = mDefaultDisplay;
                    }
                    return new WindowManagerImpl(display);
                }});

        registerService(USER_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(USER_SERVICE);
                IUserManager service = IUserManager.Stub.asInterface(b);
                return new UserManager(ctx, service);
            }});

        registerService(APP_OPS_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(APP_OPS_SERVICE);
                IAppOpsService service = IAppOpsService.Stub.asInterface(b);
                return new AppOpsManager(ctx, service);
            }});

        registerService(CAMERA_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return new CameraManager(ctx);
            }
        });

        registerService(LAUNCHER_APPS_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(LAUNCHER_APPS_SERVICE);
                ILauncherApps service = ILauncherApps.Stub.asInterface(b);
                return new LauncherApps(ctx, service);
            }
        });

        registerService(RESTRICTIONS_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(RESTRICTIONS_SERVICE);
                IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b);
                return new RestrictionsManager(ctx, service);
            }
        });
        registerService(PRINT_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE);
                IPrintManager service = IPrintManager.Stub.asInterface(iBinder);
                return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(),
                        UserHandle.getAppId(Process.myUid()));
            }});

        registerService(CONSUMER_IR_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return new ConsumerIrManager(ctx);
            }});

        registerService(MEDIA_SESSION_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return new MediaSessionManager(ctx);
            }
        });

        registerService(TRUST_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(TRUST_SERVICE);
                return new TrustManager(b);
            }
        });

        registerService(FINGERPRINT_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder binder = ServiceManager.getService(FINGERPRINT_SERVICE);
                IFingerprintService service = IFingerprintService.Stub.asInterface(binder);
                return new FingerprintManager(ctx.getOuterContext(), service);
            }
        });

        registerService(TV_INPUT_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder iBinder = ServiceManager.getService(TV_INPUT_SERVICE);
                ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder);
                return new TvInputManager(service, UserHandle.myUserId());
            }
        });

        registerService(NETWORK_SCORE_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return new NetworkScoreManager(ctx);
            }
        });

        registerService(USAGE_STATS_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder iBinder = ServiceManager.getService(USAGE_STATS_SERVICE);
                IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder);
                return new UsageStatsManager(ctx.getOuterContext(), service);
            }
        });

        registerService(JOB_SCHEDULER_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(JOB_SCHEDULER_SERVICE);
                return new JobSchedulerImpl(IJobScheduler.Stub.asInterface(b));
        }});

        registerService(PERSISTENT_DATA_BLOCK_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(PERSISTENT_DATA_BLOCK_SERVICE);
                IPersistentDataBlockService persistentDataBlockService =
                        IPersistentDataBlockService.Stub.asInterface(b);
                if (persistentDataBlockService != null) {
                    return new PersistentDataBlockManager(persistentDataBlockService);
                } else {
                    // not supported
                    return null;
                }
            }
        });

        registerService(MEDIA_PROJECTION_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    return new MediaProjectionManager(ctx);
                }
        });

        registerService(APPWIDGET_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(APPWIDGET_SERVICE);
                return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b));
        } });

        /// M: comment @{ add PerfService
        registerService(MTK_PERF_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {

                    IPerfServiceWrapper perfServiceMgr = null;
                    try {
                        perfServiceMgr = new PerfServiceWrapper(ctx);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return perfServiceMgr;
                } });
        /// @}

        /// M: Add SensorHubService @{
        if ("1".equals(SystemProperties.get("ro.mtk_sensorhub_support"))) {
            registerService(ISensorHubManager.SENSORHUB_SERVICE, new ServiceFetcher() {
                public Object createService(ContextImpl ctx) {
                    ISensorHubManager sensorhubMgr = null;
                    try {
                        IBinder b = ServiceManager.getService(ISensorHubManager.SENSORHUB_SERVICE);
                        ISensorHubService service = ISensorHubService.Stub.asInterface(b);
                        sensorhubMgr = new SensorHubManager(service);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return sensorhubMgr;
                }
            });
        }
        /// @}

    /// M: comment @{ add RnsService
        if ("1".equals(SystemProperties.get("ro.mtk_epdg_support"))) {
           registerService(RNS_SERVICE, new ServiceFetcher() {
                   public Object createService(ContextImpl ctx) {
                       IBinder b = ServiceManager.getService(RNS_SERVICE);
                       return new RnsManager(IRnsManager.Stub.asInterface(b));
                   } });
        }
        /// @}

    }


这就是我们平常调用Context.getSystemService(String arg0),因为每个系统服务实例来自 ArrayList<Object> cache = ctx.mServiceCache; 现在知道为什么调

用getSystemService(String arg0)这个函数需要强转类型了吗?因为它返回的是一个Object,所以需要强转


还有就是系统服务的管理类,我们可以看到 registerService 被调用的时候发现 IBinder b = ServiceManager.getService(ACCOUNT_SERVICE) 这样的代码

ServiceManager:

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

import com.android.internal.os.BinderInternal;

import android.util.Log;

import java.util.HashMap;
import java.util.Map;

/** @hide */
public final class ServiceManager {
    private static final String TAG = "ServiceManager";

    private static IServiceManager sServiceManager;
    private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();

    private static IServiceManager getIServiceManager() {
        if (sServiceManager != null) {
            return sServiceManager;
        }

        // Find the service manager
        sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
        return sServiceManager;
    }

    /**
     * Returns a reference to a service with the given name.
     * 
     * @param name the name of the service to get
     * @return a reference to the service, or <code>null</code> if the service doesn't exist
     */
    public static IBinder getService(String name) {
        try {
            IBinder service = sCache.get(name);
            if (service != null) {
                return service;
            } else {
                return getIServiceManager().getService(name);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "error in getService", e);
        }
        return null;
    }

    /**
     * Place a new @a service called @a name into the service
     * manager.
     * 
     * @param name the name of the new service
     * @param service the service object
     */
    public static void addService(String name, IBinder service) {
        try {
            getIServiceManager().addService(name, service, false);
        } catch (RemoteException e) {
            Log.e(TAG, "error in addService", e);
        }
    }

    /**
     * Place a new @a service called @a name into the service
     * manager.
     * 
     * @param name the name of the new service
     * @param service the service object
     * @param allowIsolated set to true to allow isolated sandboxed processes
     * to access this service
     */
    public static void addService(String name, IBinder service, boolean allowIsolated) {
        try {
            getIServiceManager().addService(name, service, allowIsolated);
        } catch (RemoteException e) {
            Log.e(TAG, "error in addService", e);
        }
    }
    
    /**
     * Retrieve an existing service called @a name from the
     * service manager.  Non-blocking.
     */
    public static IBinder checkService(String name) {
        try {
            IBinder service = sCache.get(name);
            if (service != null) {
                return service;
            } else {
                return getIServiceManager().checkService(name);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "error in checkService", e);
            return null;
        }
    }

    /**
     * Return a list of all currently running services.
     */
    public static String[] listServices() throws RemoteException {
        try {
            return getIServiceManager().listServices();
        } catch (RemoteException e) {
            Log.e(TAG, "error in listServices", e);
            return null;
        }
    }

    /**
     * This is only intended to be called when the process is first being brought
     * up and bound by the activity manager. There is only one thread in the process
     * at that time, so no locking is done.
     * 
     * @param cache the cache of service references
     * @hide
     */
    public static void initServiceCache(Map<String, IBinder> cache) {
        if (sCache.size() != 0) {
            throw new IllegalStateException("setServiceCache may only be called once");
        }
        sCache.putAll(cache);
    }
}

ServiceManagerNative

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

import java.util.ArrayList;


/**
 * Native implementation of the service manager.  Most clients will only
 * care about getDefault() and possibly asInterface().
 * @hide
 */
public abstract class ServiceManagerNative extends Binder implements IServiceManager
{
    /**
     * Cast a Binder object into a service manager interface, generating
     * a proxy if needed.
     */
    static public IServiceManager asInterface(IBinder obj)
    {
        if (obj == null) {
            return null;
        }
        IServiceManager in =
            (IServiceManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        
        return new ServiceManagerProxy(obj);
    }
    
    public ServiceManagerNative()
    {
        attachInterface(this, descriptor);
    }
    
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
    {
        try {
            switch (code) {
            case IServiceManager.GET_SERVICE_TRANSACTION: {
                data.enforceInterface(IServiceManager.descriptor);
                String name = data.readString();
                IBinder service = getService(name);
                reply.writeStrongBinder(service);
                return true;
            }
    
            case IServiceManager.CHECK_SERVICE_TRANSACTION: {
                data.enforceInterface(IServiceManager.descriptor);
                String name = data.readString();
                IBinder service = checkService(name);
                reply.writeStrongBinder(service);
                return true;
            }
    
            case IServiceManager.ADD_SERVICE_TRANSACTION: {
                data.enforceInterface(IServiceManager.descriptor);
                String name = data.readString();
                IBinder service = data.readStrongBinder();
                boolean allowIsolated = data.readInt() != 0;
                addService(name, service, allowIsolated);
                return true;
            }
    
            case IServiceManager.LIST_SERVICES_TRANSACTION: {
                data.enforceInterface(IServiceManager.descriptor);
                String[] list = listServices();
                reply.writeStringArray(list);
                return true;
            }
            
            case IServiceManager.SET_PERMISSION_CONTROLLER_TRANSACTION: {
                data.enforceInterface(IServiceManager.descriptor);
                IPermissionController controller
                        = IPermissionController.Stub.asInterface(
                                data.readStrongBinder());
                setPermissionController(controller);
                return true;
            }
            }
        } catch (RemoteException e) {
        }
        
        return false;
    }

    public IBinder asBinder()
    {
        return this;
    }
}

class ServiceManagerProxy implements IServiceManager {
    public ServiceManagerProxy(IBinder remote) {
        mRemote = remote;
    }
    
    public IBinder asBinder() {
        return mRemote;
    }
    
    public IBinder getService(String name) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeString(name);
        mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);
        IBinder binder = reply.readStrongBinder();
        reply.recycle();
        data.recycle();
        return binder;
    }

    public IBinder checkService(String name) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeString(name);
        mRemote.transact(CHECK_SERVICE_TRANSACTION, data, reply, 0);
        IBinder binder = reply.readStrongBinder();
        reply.recycle();
        data.recycle();
        return binder;
    }

    public void addService(String name, IBinder service, boolean allowIsolated)
            throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeString(name);
        data.writeStrongBinder(service);
        data.writeInt(allowIsolated ? 1 : 0);
        mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
        reply.recycle();
        data.recycle();
    }
    
    public String[] listServices() throws RemoteException {
        ArrayList<String> services = new ArrayList<String>();
        int n = 0;
        while (true) {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IServiceManager.descriptor);
            data.writeInt(n);
            n++;
            try {
                boolean res = mRemote.transact(LIST_SERVICES_TRANSACTION, data, reply, 0);
                if (!res) {
                    break;
                }
            } catch (RuntimeException e) {
                // The result code that is returned by the C++ code can
                // cause the call to throw an exception back instead of
                // returning a nice result...  so eat it here and go on.
                break;
            }
            services.add(reply.readString());
            reply.recycle();
            data.recycle();
        }
        String[] array = new String[services.size()];
        services.toArray(array);
        return array;
    }

    public void setPermissionController(IPermissionController controller)
            throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeStrongBinder(controller.asBinder());
        mRemote.transact(SET_PERMISSION_CONTROLLER_TRANSACTION, data, reply, 0);
        reply.recycle();
        data.recycle();
    }

    private IBinder mRemote;
}

IServiceManager

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

/**
 * Basic interface for finding and publishing system services.
 * 
 * An implementation of this interface is usually published as the
 * global context object, which can be retrieved via
 * BinderNative.getContextObject().  An easy way to retrieve this
 * is with the static method BnServiceManager.getDefault().
 * 
 * @hide
 */
public interface IServiceManager extends IInterface
{
    /**
     * Retrieve an existing service called @a name from the
     * service manager.  Blocks for a few seconds waiting for it to be
     * published if it does not already exist.
     */
    public IBinder getService(String name) throws RemoteException;
    
    /**
     * Retrieve an existing service called @a name from the
     * service manager.  Non-blocking.
     */
    public IBinder checkService(String name) throws RemoteException;

    /**
     * Place a new @a service called @a name into the service
     * manager.
     */
    public void addService(String name, IBinder service, boolean allowIsolated)
                throws RemoteException;

    /**
     * Return a list of all currently running services.
     */
    public String[] listServices() throws RemoteException;

    /**
     * Assign a permission controller to the service manager.  After set, this
     * interface is checked before any services are added.
     */
    public void setPermissionController(IPermissionController controller)
            throws RemoteException;
    
    static final String descriptor = "android.os.IServiceManager";

    int GET_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION;
    int CHECK_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+1;
    int ADD_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+2;
    int LIST_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+3;
    int CHECK_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+4;
    int SET_PERMISSION_CONTROLLER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+5;
}


 IInterface

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.os;

/**
 * Base class for Binder interfaces.  When defining a new interface,
 * you must derive it from IInterface.
 */
public interface IInterface
{
    /**
     * Retrieve the Binder object associated with this interface.
     * You must use this instead of a plain cast, so that proxy objects
     * can return the correct result.
     */
    public IBinder asBinder();
}

这就是大致的流程,关于获取系统服务的实例,我也把相关的源码贴上了,大家可以了解一下。
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页