Example usage for android.content.pm PackageManager queryBroadcastReceivers

List of usage examples for android.content.pm PackageManager queryBroadcastReceivers

Introduction

In this page you can find the example usage for android.content.pm PackageManager queryBroadcastReceivers.

Prototype

public abstract List<ResolveInfo> queryBroadcastReceivers(Intent intent, @ResolveInfoFlags int flags);

Source Link

Document

Retrieve all receivers that can handle a broadcast of the given intent.

Usage

From source file:com.onesignal.GenerateNotification.java

static void setStatics(Context inContext) {
    currentContext = inContext;//from  ww w  . jav a  2  s  . c o m
    packageName = currentContext.getPackageName();
    contextResources = currentContext.getResources();

    PackageManager packageManager = currentContext.getPackageManager();
    Intent intent = new Intent(currentContext, NotificationOpenedReceiver.class);
    intent.setPackage(currentContext.getPackageName());
    if (packageManager.queryBroadcastReceivers(intent, 0).size() > 0) {
        openerIsBroadcast = true;
        notificationOpenedClass = NotificationOpenedReceiver.class;
    } else
        notificationOpenedClass = NotificationOpenedActivity.class;
}

From source file:org.totschnig.myexpenses.util.Utils.java

public static boolean isIntentReceiverAvailable(Context context, Intent intent) {
    final PackageManager packageManager = context.getPackageManager();
    List<ResolveInfo> list = packageManager.queryBroadcastReceivers(intent, 0);
    return !list.isEmpty();
}

From source file:com.onesignal.OneSignal.java

private static void fireIntentFromNotificationOpen(Context inContext, JSONArray data) {
    PackageManager packageManager = inContext.getPackageManager();

    boolean isCustom = false;

    Intent intent = new Intent().setAction("com.onesignal.NotificationOpened.RECEIVE")
            .setPackage(inContext.getPackageName());

    List<ResolveInfo> resolveInfo = packageManager.queryBroadcastReceivers(intent,
            PackageManager.GET_INTENT_FILTERS);
    if (resolveInfo.size() > 0) {
        intent.putExtra("onesignal_data", data.toString());
        inContext.sendBroadcast(intent);
        isCustom = true;//from www.j a  va2 s . co  m
    }

    // Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag.
    resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (resolveInfo.size() > 0) {
        if (!isCustom)
            intent.putExtra("onesignal_data", data.toString());
        isCustom = true;
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        inContext.startActivity(intent);
    }

    if (!isCustom) {
        try {
            ApplicationInfo ai = inContext.getPackageManager().getApplicationInfo(inContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            String defaultStr = bundle.getString("com.onesignal.NotificationOpened.DEFAULT");
            isCustom = "DISABLE".equals(defaultStr);
        } catch (Throwable t) {
            Log(LOG_LEVEL.ERROR, "", t);
        }
    }

    if (!isCustom) {
        Intent launchIntent = inContext.getPackageManager()
                .getLaunchIntentForPackage(inContext.getPackageName());

        if (launchIntent != null) {
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            inContext.startActivity(launchIntent);
        }
    }
}

From source file:com.github.michalbednarski.intentslab.editor.ComponentPickerDialogFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);//from w w w . j a v  a  2  s  .  com

    // Get edited intent
    IntentEditorActivity intentEditor = (IntentEditorActivity) getActivity();
    Intent intent = new Intent(intentEditor.getEditedIntent());
    intent.setComponent(null);

    // Get components
    PackageManager pm = intentEditor.getPackageManager();
    List<ResolveInfo> ri = null;

    switch (intentEditor.getComponentType()) {
    case IntentEditorConstants.ACTIVITY:
        ri = pm.queryIntentActivities(intent, PackageManager.GET_DISABLED_COMPONENTS);
        break;
    case IntentEditorConstants.BROADCAST:
        ri = pm.queryBroadcastReceivers(intent, PackageManager.GET_DISABLED_COMPONENTS);
        break;
    case IntentEditorConstants.SERVICE:
        ri = pm.queryIntentServices(intent, PackageManager.GET_DISABLED_COMPONENTS);
        break;
    }

    // Cancel if no components
    if (ri.isEmpty()) {
        Toast.makeText(getActivity(), R.string.no_matching_components_found, Toast.LENGTH_SHORT).show();
        dismiss();
        return;
    }

    // Split enabled and disabled choices
    ArrayList<ResolveInfo> choices = new ArrayList<ResolveInfo>();
    ArrayList<ResolveInfo> disabledChoices = new ArrayList<ResolveInfo>();
    for (ResolveInfo resolveInfo : ri) {
        (isComponentEnabled(pm, resolveInfo) ? choices : disabledChoices).add(resolveInfo);
    }

    mEnabledChoicesCount = choices.size();
    choices.addAll(disabledChoices);
    mChoices = choices.toArray(new ResolveInfo[choices.size()]);
}

From source file:com.anysoftkeyboard.addons.AddOnsFactory.java

private List<E> getExternalAddOns() {
    if (!mReadExternalPacksToo)//this will disable external packs (API careful stage)
        return Collections.emptyList();

    final PackageManager packageManager = mContext.getPackageManager();
    final List<ResolveInfo> broadcastReceivers = packageManager
            .queryBroadcastReceivers(new Intent(mReceiverInterface), PackageManager.GET_META_DATA);

    final List<E> externalAddOns = new ArrayList<>();

    for (final ResolveInfo receiver : broadcastReceivers) {
        if (receiver.activityInfo == null) {
            Logger.e(mTag, "BroadcastReceiver has null ActivityInfo. Receiver's label is "
                    + receiver.loadLabel(packageManager));
            Logger.e(mTag, "Is the external keyboard a service instead of BroadcastReceiver?");
            // Skip to next receiver
            continue;
        }//  www  .  j a va  2 s  .co  m

        if (!receiver.activityInfo.enabled || !receiver.activityInfo.applicationInfo.enabled)
            continue;

        try {
            final Context externalPackageContext = mContext
                    .createPackageContext(receiver.activityInfo.packageName, Context.CONTEXT_IGNORE_SECURITY);
            final List<E> packageAddOns = getAddOnsFromActivityInfo(externalPackageContext,
                    receiver.activityInfo);

            externalAddOns.addAll(packageAddOns);
        } catch (final NameNotFoundException e) {
            Logger.e(mTag, "Did not find package: " + receiver.activityInfo.packageName);
        }

    }

    return externalAddOns;
}

From source file:com.android.tv.settings.users.AppRestrictionsFragment.java

private void populateApps() {
    final Context context = getActivity();
    if (context == null)
        return;//from w w  w  .  ja  va2  s .  c o  m
    final PackageManager pm = mPackageManager;
    final int userId = mUser.getIdentifier();

    // Check if the user was removed in the meantime.
    if (getExistingUser(mUserManager, mUser) == null) {
        return;
    }
    mAppList.removeAll();
    addLocationAppRestrictionsPreference();
    Intent restrictionsIntent = new Intent(Intent.ACTION_GET_RESTRICTION_ENTRIES);
    final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(restrictionsIntent, 0);
    for (AppRestrictionsHelper.SelectableAppInfo app : mHelper.getVisibleApps()) {
        String packageName = app.packageName;
        if (packageName == null)
            continue;
        final boolean isSettingsApp = packageName.equals(context.getPackageName());
        AppRestrictionsPreference p = new AppRestrictionsPreference(getPreferenceManager().getContext());
        final boolean hasSettings = resolveInfoListHasPackage(receivers, packageName);
        if (isSettingsApp) {
            // Settings app should be available to restricted user
            mHelper.setPackageSelected(packageName, true);
            continue;
        }
        PackageInfo pi = null;
        try {
            pi = mIPm.getPackageInfo(packageName,
                    PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.GET_SIGNATURES, userId);
        } catch (RemoteException e) {
            // Ignore
        }
        if (pi == null) {
            continue;
        }
        if (mRestrictedProfile && isAppUnsupportedInRestrictedProfile(pi)) {
            continue;
        }
        p.setIcon(app.icon != null ? app.icon.mutate() : null);
        p.setChecked(false);
        p.setTitle(app.activityName);
        p.setKey(getKeyForPackage(packageName));
        p.setPersistent(false);
        p.setOnPreferenceChangeListener(this);
        p.setSummary(getPackageSummary(pi, app));
        if (pi.requiredForAllUsers || isPlatformSigned(pi)) {
            p.setChecked(true);
            p.setImmutable(true);
            // If the app is required and has no restrictions, skip showing it
            if (!hasSettings)
                continue;
        } else if (!mNewUser && isAppEnabledForUser(pi)) {
            p.setChecked(true);
        }
        if (app.masterEntry == null && hasSettings) {
            requestRestrictionsForApp(packageName, p);
        }
        if (app.masterEntry != null) {
            p.setImmutable(true);
            p.setChecked(mHelper.isPackageSelected(packageName));
        }
        p.setOrder(MAX_APP_RESTRICTIONS * (mAppList.getPreferenceCount() + 2));
        mHelper.setPackageSelected(packageName, p.isChecked());
        mAppList.addPreference(p);
    }
    mAppListChanged = true;
    // If this is the first time for a new profile, install/uninstall default apps for profile
    // to avoid taking the hit in onPause(), which can cause race conditions on user switch.
    if (mNewUser && mFirstTime) {
        mFirstTime = false;
        mHelper.applyUserAppsStates(this);
    }
}

From source file:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

    // Get the local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    mBluetoothDevice = null;/*  w  w  w . j  ava2 s.c o  m*/

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

From source file:com.androzic.Androzic.java

public void initializeOnlineMapProviders() {
    PackageManager packageManager = getPackageManager();

    Intent initializationIntent = new Intent("com.androzic.map.online.provider.action.INITIALIZE");
    // enumerate online map providers
    List<ResolveInfo> providers = packageManager.queryBroadcastReceivers(initializationIntent, 0);
    for (ResolveInfo provider : providers) {
        // send initialization broadcast, we send it directly instead of sending
        // one broadcast for all plugins to wake up stopped plugins:
        // http://developer.android.com/about/versions/android-3.1.html#launchcontrols
        Intent intent = new Intent();
        intent.setClassName(provider.activityInfo.packageName, provider.activityInfo.name);
        intent.setAction(initializationIntent.getAction());
        sendBroadcast(intent);/*w  w  w.  j  ava 2 s.c o  m*/

        List<TileProvider> tileProviders = TileProviderFactory.fromPlugin(packageManager, provider);
        for (TileProvider tileProvider : tileProviders) {
            tileProvider.tileExpiration = onlineMapTileExpiration;
        }
        onlineMaps.addAll(tileProviders);
    }
}

From source file:com.androzic.Androzic.java

public void initializePlugins() {
    PackageManager packageManager = getPackageManager();
    List<ResolveInfo> plugins;
    Intent initializationIntent = new Intent("com.androzic.plugins.action.INITIALIZE");

    // enumerate initializable plugins
    plugins = packageManager.queryBroadcastReceivers(initializationIntent, 0);
    for (ResolveInfo plugin : plugins) {
        // send initialization broadcast, we send it directly instead of sending
        // one broadcast for all plugins to wake up stopped plugins:
        // http://developer.android.com/about/versions/android-3.1.html#launchcontrols
        Intent intent = new Intent();
        intent.setClassName(plugin.activityInfo.packageName, plugin.activityInfo.name);
        intent.setAction(initializationIntent.getAction());
        sendBroadcast(intent);/*w w w .jav a 2 s  .c o m*/
    }

    // enumerate plugins with preferences
    plugins = packageManager.queryIntentActivities(new Intent("com.androzic.plugins.preferences"), 0);
    for (ResolveInfo plugin : plugins) {
        Intent intent = new Intent();
        intent.setClassName(plugin.activityInfo.packageName, plugin.activityInfo.name);
        pluginPreferences.put(plugin.activityInfo.loadLabel(packageManager).toString(), intent);
    }

    // enumerate plugins with views
    plugins = packageManager.queryIntentActivities(new Intent("com.androzic.plugins.view"), 0);
    for (ResolveInfo plugin : plugins) {
        // get menu icon
        Drawable icon = null;
        try {
            Resources resources = packageManager
                    .getResourcesForApplication(plugin.activityInfo.applicationInfo);
            int id = resources.getIdentifier("ic_menu_view", "drawable", plugin.activityInfo.packageName);
            if (id != 0)
                icon = resources.getDrawable(id);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent();
        intent.setClassName(plugin.activityInfo.packageName, plugin.activityInfo.name);
        Pair<Drawable, Intent> pair = new Pair<>(icon, intent);
        pluginViews.put(plugin.activityInfo.loadLabel(packageManager).toString(), pair);
    }
}