2016-02-05 122 views
2

我在用戶配置文件以及託管配置文件(AFW)中都有一個應用程序。我試圖根據包名發送廣播。 intent.setPackage(packageName); mContext.sendBroadcastAsUser(intent,UserHandle.ALL);將系統廣播發送到僅託管配置文件應用程序

結果是應用程序(用戶和託管配置文件)都獲得廣播。

我想發送廣播只管理配置文件的應用程序(所以基本上用戶配置文件不應該收到)

+0

我想問你如果你能夠執行mContext.sendBroadcastAsUser(intent,UserHandle.ALL);我讀過它只能用於系統應用程序(是真的嗎?) – Sam

+0

是的,我能夠執行並且您是對的。 mContext.sendBroadcastAsUser(intent,UserHandle.ALL)只能從系統應用程序訪問。我從PhoneWindowManager發送此廣播。 –

回答

1

它可以發送廣播只管理配置文件如果能夠獲得管理配置文件的用戶ID。

現在要獲得用戶ID,我們需要監聽添加的託管配置文件的廣播。

Intent.ACTION_MANAGED_PROFILE_ADDED 

步驟註冊監聽這個廣播,

IntentFilter filter = new IntentFilter(); 
filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 
filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED); 
context.registerReceiver(mManagedProfileListener, filter); 

現在裏面的onReceive,如何獲得用戶ID,

@Override 
public void onReceive(Context context, Intent intent) { 
    if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(intent.getAction()) 
     && intent.hasExtra(Intent.EXTRA_USER)) { 
     UserHandle handle = intent.getExtras().getParcelable(Intent.EXTRA_USER); 
     userid = handle.getIdentifier(); 
    } 
} 

現在發送廣播到用戶ID(只有系統能發送這個廣播),

mContext.sendBroadcastAsUser(intent, new UserHandle(userid)); 

注意:userid實際上是在設備上配置了託管配置文件或AFW(Android For Work)時在/ data/user下創建的文件夾名稱。

相關問題