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));
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值