下面列出了怎么用android.view.IRotationWatcher的API类实例代码及写法,或者点击链接到github查看源代码。
public LegacySensorManager(SensorManager sensorManager) {
mSensorManager = sensorManager;
synchronized (SensorManager.class) {
if (!sInitialized) {
sWindowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
if (sWindowManager != null) {
// if it's null we're running in the system process
// which won't get the rotated values
try {
sRotation = sWindowManager.watchRotation(
new IRotationWatcher.Stub() {
public void onRotationChanged(int rotation) {
LegacySensorManager.onRotationChanged(rotation);
}
}, DEFAULT_DISPLAY);
} catch (RemoteException e) {
}
}
}
}
}
/** Register an {@link IRotationWatcher} with IWindowManager. */
protected static boolean watchRotations(IRotationWatcher watcher, final boolean watch) {
// NOTE: removeRotationWatcher is only available on Android 4.3 (API 18) and 4.4 (API 19 & 20).
final String methodName = ((watch) ? "watchRotation" : "removeRotationWatcher" );
final IInterface mWM = getIWindowManager();
if (null == mWM) return false;
try {
Method mMethod = mWM.getClass().getDeclaredMethod(
methodName, new Class[]{ IRotationWatcher.class });
if (mMethod == null) return false;
mMethod.setAccessible(true);
mMethod.invoke(mWM, watcher);
return true;
} catch (Throwable t) {
Log.e(TAG, "Cannot register " + IRotationWatcher.class.getSimpleName() , t);
return false;
}
}
/** Register an {@link IRotationWatcher} with IWindowManager. */
protected static boolean watchRotations(IRotationWatcher watcher, final boolean watch) {
// NOTE: removeRotationWatcher is only available on Android 4.3 (API 18) and 4.4 (API 19 & 20).
final String methodName = ((watch) ? "watchRotation" : "removeRotationWatcher" );
final IInterface mWM = getIWindowManager();
if (null == mWM) return false;
try {
Method mMethod = mWM.getClass().getDeclaredMethod(
methodName, new Class[]{ IRotationWatcher.class });
if (mMethod == null) return false;
mMethod.setAccessible(true);
mMethod.invoke(mWM, watcher);
return true;
} catch (Throwable t) {
Log.e(TAG, "Cannot register " + IRotationWatcher.class.getSimpleName() , t);
return false;
}
}
void setRotateListener(RotateListener listener) {
try {
Class<?> clazz = iWindowManager.getClass();
IRotationWatcher watcher =
new IRotationWatcher.Stub() {
@Override
public void onRotationChanged(int rotation) throws RemoteException {
if (listener != null) {
listener.onRotate(rotation);
}
}
};
try {
clazz.getMethod("watchRotation", IRotationWatcher.class, int.class)
.invoke(iWindowManager, watcher, Display.DEFAULT_DISPLAY); // 26+
} catch (NoSuchMethodException ex) {
clazz.getMethod("watchRotation", IRotationWatcher.class)
.invoke(iWindowManager, watcher);
}
} catch (Exception e) {
e.printStackTrace();
}
}