androidandroid-for-work

Send system broadcasts to only Managed profile applications


I am having a app in both user profile as well as managed profile (AFW). I am trying to send broadcast based on package name. intent.setPackage(packageName); mContext.sendBroadcastAsUser(intent, UserHandle.ALL);

Result is both apps (user and managed profiles) get the broadcast.

I want to send broadcast to only managed profile app (So basically user profile should not receive the )


Solution

  • Its possible to send broadcast only to managed profile if we can get managed profile userid.

    Now to get userid, we need to listen to broadcast of Managed Profile added.

    Intent.ACTION_MANAGED_PROFILE_ADDED
    

    Steps to register to listen for this broadcast,

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

    Now inside onReceive, how to get userid,

    @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();
       }
    }
    

    Now send broadcast to that userid (only system can send this broadcast),

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

    Note: userid is actually the folder name which is created under /data/user whenever a managed profile or AFW (Android For Work) is configured on device.