Android代码异常Calling a method in the system process without a qualified user

问题原因:

有时候发现,startService或者sendBroadCast会产生此异常:在没有合格用户的情况下调用系统进程中的方法。经查,原因是由于系统应用尝试拉起普通应用抛出此异常,可能是在Android 4.2 之后Android引入多用户支持,有些特殊权限启动服务或者发送广播会失败。

如何修改:

即把之前的启动服务,或者发送广播改为下面的调用方式即可:

public void startActivityAsUser(Intent intent, UserHandle user); 
public void sendBroadcastAsUser(Intent intent, UserHandle user); 
public ComponentName startServiceAsUser(Intent service, UserHandle user); 
public boolean stopServiceAsUser(Intent service, UserHandle user); 

UserHandle.ALL 
UserHandle.CURRENT 
UserHandle.CURRENT_OR_SELF
UserHandle.OWNER

其中:

/** A user handle to indicate all users on the device */  
//设备上所有用户均可接收到广播  
// handle = -1  
UserHandle.ALL  
  
/** A user handle to indicate the current user of the device */  
//设备上当前用户可接收到广播  
// handle = -2  
UserHandle.CURRENT  
  
/** A user handle to indicate that we would like to send to the current 
 *  user, but if this is calling from a user process then we will send it 
 *  to the caller's user instead of failing wiht a security exception */  
//handle = -3  
//设备上当前用户或者该应用所属用户可接收到广播  
UserHandle.CURRENT_OR_SELF  
  
/** A user handle to indicate the primary/owner user of the device */  
// handle = 0  
//设备所有者可接收到广播  
UserHandle.OWNER 

例如:

Intent intent = new Intent();
intent.setAction("com.android.server.light.brightness");
intent.putExtra("brightness", brightness);
//send broadcast

// mContext.sendBroadcast(intent);   --舍弃
// mContext.sendBroadcastAsUser(intent, UserHandle.ALL);

如果调用不到,不妨看看源码修改:

context.sendBroadcastAsUser(intent, UserHandle.getUserHandleForUid(-1));

Parcel parcel = Parcel.obtain();
parcel.writeInt(-1);
context.sendBroadcastAsUser(null, new UserHandle(parcel));

猜你喜欢

转载自blog.csdn.net/Jason_Lee155/article/details/125843832