0.現(xiàn)象描述
比如華為幔欧,三星,魅族等一些手機(jī)娜遵,如果關(guān)閉某個(gè)應(yīng)用的通知權(quán)限蜕衡,然后應(yīng)用類的toast就無法打出來了,表示很無解设拟,難道要自己做一個(gè)view給用戶提示嗎慨仿?答案是當(dāng)然不需要,還可以拯救一下纳胧。镰吆。。
1.導(dǎo)致無法彈出toast的原因
為了查一下原因跑慕,我們先去看看源碼万皿,下圖是Toast的show方法
/**
* Show the view for the specified duration.
*/
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getOpPackageName();
TN tn = mTN;
tn.mNextView = mNextView;
try {
service.enqueueToast(pkg, tn, mDuration);
} catch (RemoteException e) {
// Empty
}
}
Toast中的show()方法,show方法中調(diào)用 service.enqueueToast(pkg, tn, mDuration); 那么service是什么呢核行?下面看看getService()的方法牢硅。
static private INotificationManager getService() {
if (sService != null) {
return sService;
}
sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
return sService;
}
INotificationManager 是跨進(jìn)程通信的 Binder 類,sService 是 NMS(NotificationManagerService) 在客戶端的代理钮科,發(fā)送通知要委托給 sService唤衫,由它傳遞給 NMS婆赠,這里獲取了遠(yuǎn)程的一個(gè)服務(wù)绵脯,用來調(diào)用遠(yuǎn)程的enqueueToast方法。
接下來看看NotificationManagerService.java中的enqueueToast方法休里,源碼如下:
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
if (DBG) {
Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
}
if (pkg == null || callback == null) {
Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
return ;
}
final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
final boolean isPackageSuspended = isPackageSuspendedForUser(pkg, Binder.getCallingUid());
if (ENABLE_BLOCKED_TOASTS && (!noteNotificationOp(pkg, Binder.getCallingUid())
|| isPackageSuspended)) {
if (!isSystemToast) {
Slog.e(TAG, "Suppressing toast from package " + pkg
+ (isPackageSuspended? " due to package suspended by administrator." : " by user request."));
return;
}
}
synchronized (mToastQueue) {
int callingPid = Binder.getCallingPid();
long callingId = Binder.clearCallingIdentity();
try {
ToastRecord record;
int index = indexOfToastLocked(pkg, callback);
// If it's already in the queue, we update it in place, we don't
// move it to the end of the queue.
if (index >= 0) {
record = mToastQueue.get(index);
record.update(duration);
} else {
// Limit the number of toasts that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemToast) {
int count = 0;
final int N = mToastQueue.size();
for (int i=0; i<N; i++) {
final ToastRecord r = mToastQueue.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " toasts. Not showing more. Package=" + pkg);
return;
}
}
}
}
record = new ToastRecord(callingPid, pkg, callback, duration);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
keepProcessAliveLocked(callingPid);
}
// If it's at index 0, it's the current toast. It doesn't matter if it's
// new or just been updated. Call back and tell it to show itself.
// If the callback fails, this will remove it from the list, so don't
// assume that it's valid after this.
if (index == 0) {
showNextToastLocked();
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}
從以上代碼可知蛆挫,如果noteNotificationOp()方法返回了false,也就是這個(gè)包名的通知權(quán)限被禁用妙黍,那么就會(huì)return悴侵,致使無法彈出Toast!
2.怎么解決
參考網(wǎng)絡(luò)上的一些解決方案, 如下方案是把pkg名字改成“android”拭嫁,這樣就不用管權(quán)限了可免。
/**
* 顯示系統(tǒng)Toast
*/
private static void showSystemToast(Toast toast){
try{
Method getServiceMethod = Toast.class.getDeclaredMethod("getService");
getServiceMethod.setAccessible(true);
final Object iNotificationManager = getServiceMethod.invoke(null);
Class iNotificationManagerCls = Class.forName("android.app.INotificationManager");
Object iNotificationManagerProxy = Proxy.newProxyInstance(toast.getClass().getClassLoader(), new Class[]{iNotificationManagerCls}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 強(qiáng)制使用系統(tǒng)Toast
// 華為p20 pro上為enqueueToastEx
if("enqueueToast".equals(method.getName())
|| "enqueueToastEx".equals(method.getName())){
args[0] = "android";
}
return method.invoke(iNotificationManager, args);
}
});
Field sServiceFiled = Toast.class.getDeclaredField("sService");
sServiceFiled.setAccessible(true);
sServiceFiled.set(null, iNotificationManagerProxy);
toast.show();
}catch (Exception e){
e.printStackTrace();
}
}