Android通过反射机制实现打开关闭通知栏

之前用iPhone的时候,iPhone的Assisitivetouch中有一个通知中心选项,点击通知中心就会自动打开通知栏,在手机屏幕越来越大的今天,这个功能还是很实用的,现在用Android手机了,想着是不是可以在Android手机上也实现一个类似的功能,研究了一下发现Android的打开通知栏的方法是没有对普通用户开放的,也就是说我们不能够直接在代码中去调用打开通知栏的方法,只能通过反射机制来获取打开通知栏的方法进行调用,反射打开通知栏代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private void handleNotify(String hanlde) {
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
try {
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class
.forName("android.app.StatusBarManager");
Method expand = null;
if (service != null) {
if (currentApiVersion <= 16) {
expand = statusbarManager.getMethod("expand");
} else {
if (hanlde == "open") {
expand = statusbarManager
.getMethod("expandNotificationsPanel");
} else if (hanlde == "close") {
expand = statusbarManager
.getMethod("collapsePanels");
}
}
expand.setAccessible(true);
expand.invoke(service);
}
} catch (Exception e) {
Log.d("caobin", "error");
}
}

注意有三点需要注意:

  1. 在执行Object service = getSystemService(“statusbar”);这句的时候,可能会提示参数错误,说是参数只能是Context.xxxService之类的,忽略一下就好。

  2. 因为在Android4.1(API 16)之后,打开通知栏的方法名由expand改成expandNotificationsPanel了,所以为了保证程序在所有的手机上都能够正常工作,需要加上api的判断。

  3. 关闭通知栏的方法是collapsePanels,调用该方法会自动关闭打开的通知栏。

附上项目demo地址:反射方法调用打开关闭通知栏