Example usage for android.content.pm PackageManager setComponentEnabledSetting

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

Introduction

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

Prototype

public abstract void setComponentEnabledSetting(@NonNull ComponentName componentName,
        @EnabledState int newState, @EnabledFlags int flags);

Source Link

Document

Set the enabled setting for a package component (activity, receiver, service, provider).

Usage

From source file:com.android.tv.receiver.BootCompletedReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (DEBUG)//from ww  w  . j a  va 2s .  c  o m
        Log.d(TAG, "boot completed " + intent);
    // Start {@link NotificationService}.
    Intent notificationIntent = new Intent(context, NotificationService.class);
    notificationIntent.setAction(NotificationService.ACTION_SHOW_RECOMMENDATION);
    context.startService(notificationIntent);

    // Grant permission to already set up packages after the system has finished booting.
    SetupUtils.grantEpgPermissionToSetUpPackages(context);

    if (Features.UNHIDE.isEnabled(context)) {
        if (OnboardingUtils.isFirstBoot(context)) {
            // Enable the application if this is the first "unhide" feature is enabled just in
            // case when the app has been disabled before.
            PackageManager pm = context.getPackageManager();
            ComponentName name = new ComponentName(context, TvActivity.class);
            if (pm.getComponentEnabledSetting(name) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
            }
            OnboardingUtils.setFirstBootCompleted(context);
        }
    }

    if (CommonFeatures.DVR.isEnabled(context) && BuildCompat.isAtLeastN()) {
        DvrRecordingService.startService(context);
    }
}

From source file:com.kyleszombathy.sms_scheduler.MessageAlarmReceiver.java

/** Method to set a new alarm
 * @param context The app context/*from  w w  w .j av  a2s . c  o  m*/
 * @param timeToSend The Time to send the message (in Calendar format)
 * @param phoneNumberList String Arraylist of phone numbers
 * @param messageContent The content of the message you want to send
 * @param alarmNumber Provide an identifier for the alarm
 * @param nameList The list of names, corresponding with the phone numbers*/
public void createAlarm(Context context, Calendar timeToSend, ArrayList<String> phoneNumberList,
        String messageContent, int alarmNumber, ArrayList<String> nameList) {
    this.context = context;

    // Creates new alarm
    alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(context, MessageAlarmReceiver.class);

    // Add extras
    Bundle extras = new Bundle();
    extras.putStringArrayList("pNum", phoneNumberList);
    extras.putString("message", messageContent);
    extras.putInt("alarmNumber", alarmNumber);
    extras.putStringArrayList("nameList", nameList);
    intentAlarm.putExtras(extras);

    // Set alarm
    pendingIntent = PendingIntent.getBroadcast(context, alarmNumber, intentAlarm,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarm.set(AlarmManager.RTC_WAKEUP, timeToSend.getTimeInMillis(), pendingIntent);

    // Enable {@code MessageBootReceiver} to automatically restart the alarm when the
    // device is rebooted.
    ComponentName receiver = new ComponentName(context, MessageBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    Log.i(TAG, "createAlarm: Alarm Created. alarmNumber: " + alarmNumber);
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

/**
 * This function creates a new Alarm by given alarm type. if not {@link AlarmType#NONE}
 * value was given as a type alarm will be called Daily, Weekly or Monthly staring from
 * time when this function was called. All alarms which were created before will be canceled.
 *
 * @param context Application context/*from ww w  .  ja  va 2 s  .c  o  m*/
 * @param type Alarm Type, accepted values are
 *              {@link AlarmType#NONE} if need to cancel all alarms,
 *              {@link AlarmType#DAILY} alarm will called daily
 *              {@link AlarmType#WEEKLY} alarm will called weekly
 *              {@link AlarmType#MONTHLY} alarm will called monthly
 */
public static void createAlarm(final Context context, AlarmType type) {

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    switch (type) {
    case DAILY:
        calendar.add(Calendar.DATE, 1);
        break;

    case WEEKLY:
        calendar.add(Calendar.DATE, 7);
        break;

    case MONTHLY:
        calendar.add(Calendar.MONTH, 1);
        break;
    }

    // Create Alarm Manager Object.
    if (mAlarmManager == null)
        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //
    Intent intent = new Intent(context, AlarmReceiver.class);
    if (mAlarmIntent == null)
        mAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    // Remove all previously created alarms, before creating new one.
    if (mAlarmManager != null) {
        mAlarmManager.cancel(mAlarmIntent);

        // By default Disable Boot Receiver.
        int componentEnabledState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
        // For enabling/disabling Boot Receiver.
        ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
        PackageManager pm = context.getPackageManager();

        // Set new alarm if provided interval is not none.
        if (!AlarmType.NONE.equals(type)) {
            Logger.debug("AlarmReceiver", String
                    .format("----> Next Update Date: %1$tA %1$tb %1$td %1$tY at %1$tI:%1$tM %1$Tp", calendar));
            // Enables Boot Receiver.
            componentEnabledState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
            // Set repeating alarm.
            final long timeInMillis = calendar.getTimeInMillis();
            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, type.getValue(),
                    mAlarmIntent);

            // Stores next Alert Time.
            PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, timeInMillis);

        } else {
            PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        }

        pm.setComponentEnabledSetting(receiver, componentEnabledState, PackageManager.DONT_KILL_APP);
    }
}

From source file:com.github.michalbednarski.intentslab.StartActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        startActivity(new Intent(this, PrefsActivity.class));
        return true;
    case R.id.interception: {
        final PackageManager packageManager = getPackageManager();
        boolean enable = packageManager.getComponentEnabledSetting(
                mInterceptActivityComponentName) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED;

        packageManager
                .setComponentEnabledSetting(mInterceptActivityComponentName,
                        enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);

        Toast.makeText(this,
                enable ? getString(R.string.interception_enabled) : getString(R.string.interception_disabled),
                Toast.LENGTH_SHORT).show();
        ActivityCompat.invalidateOptionsMenu(this);
        return true;
    }//from ww  w  .j  av  a2 s  . c o m
    case R.id.system_services:
        (new SystemServicesDialog()).show(getSupportFragmentManager(), "systemServices");
        return true;
    case R.id.provider_lab:
        startActivity(new Intent(StartActivity.this, AdvancedQueryActivity.class));
        return true;
    }
    return false;
}

From source file:com.yacorso.nowaste.views.activities.DrawerActivity.java

/**
 * Enable every day local notification/*from   w  w  w . j av  a  2 s. co m*/
 */
private void enableNotificationReceiver() {
    Context context = getApplicationContext();
    ComponentName receiver = new ComponentName(context, BootCompletedReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    Intent serviceIntent = new Intent(context, NotificationService.class);
    context.stopService(serviceIntent);

    AlarmReceiver alarmReceiver = new AlarmReceiver();
    alarmReceiver.setAlarm(context);
}

From source file:com.soft.pushsender.DemoActivity.java

private void enPush() {
    //Enable push notifications
    ComponentName receiver = new ComponentName(context, GcmBroadcastReceiver.class);

    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:org.traccar.client.MainFragment.java

private void removeLauncherIcon() {
    String className = MainActivity.class.getCanonicalName().replace(".MainActivity", ".Launcher");
    ComponentName componentName = new ComponentName(getActivity().getPackageName(), className);
    PackageManager packageManager = getActivity().getPackageManager();
    if (packageManager
            .getComponentEnabledSetting(componentName) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
        packageManager.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setMessage(getString(R.string.hidden_alert));
        builder.setPositiveButton(android.R.string.ok, null);
        builder.show();/*from ww  w.ja v a2 s .  co m*/
    }
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    if (context == null || intent == null) {
        Logger.error("AlarmReceiver", "onReceive(Context " + (context == null ? "null," : ",") + " Intent "
                + (intent == null ? "null)" : ")"));
        return;/*from w w  w .  j a  v a2 s.  c  o m*/
    }

    // Set Context
    mContext = context;

    // Get shared preferences.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    // Check internet availability and only in that case start actions.
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    final String action = intent.getAction();
    // Catch Network change state.
    if (!TextUtils.isEmpty(action) && action.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
        // If internet connection established
        if (isConnected) {
            // If didn't missed last update of data due to network issues do nothing,
            // otherwise proceed with data updating.
            final boolean missUpdateDueToNetworkIssue = sp
                    .getBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, false);
            if (!missUpdateDueToNetworkIssue)
                return;
        }
        // If user switch off Internet connection do not proceed.
        else
            return;
    }
    // Check Boot state.
    else if (!TextUtils.isEmpty(action) && action.equals("android.intent.action.BOOT_COMPLETED")) {
        // Get stored alarm time.
        final long nextAlarmTime = PreferenceUtils.getDataLong(context,
                PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        if (nextAlarmTime != -1) {
            // Set new alarm, as after reboot alarm was switched off.
            if (mAlarmManager == null)
                mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            if (mAlarmIntent == null)
                mAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

            // Enable boot receiver
            ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            final int ui = DialogSettings.getUpdateInterval(context);
            AlarmType type = ui == DialogSettings.DAILY ? AlarmType.DAILY
                    : ui == DialogSettings.WEEKLY ? AlarmType.WEEKLY : AlarmType.MONTHLY;

            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTime, type.getValue(),
                    mAlarmIntent);
        }
        return;
    }
    // When alarm rise we appears in the block below.
    else {
        Logger.beep();
        Logger.beep();
        Logger.beep();
        // Calculating next alarm time.
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        final int updateInterval = DialogSettings.getUpdateInterval(context);
        if (updateInterval == DialogSettings.DAILY)
            calendar.add(Calendar.DATE, 1);
        else if (updateInterval == DialogSettings.WEEKLY)
            calendar.add(Calendar.DATE, 7);
        else if (updateInterval == DialogSettings.MONTHLY)
            calendar.add(Calendar.MONTH, 1);
        else
            Logger.error("AlarmReceiver", "Unknown Update Interval.");

        // Next alarm time.
        final long nextAlarmTimeInMillis = calendar.getTimeInMillis();
        // Store next alarm time for further use.
        PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, nextAlarmTimeInMillis);
    }

    if (!isConnected) {
        Logger.debug("AlarmReceiver", "No Internet connection, while receiving Alarm message");
        // If no internet connecting schedule data update, as soon
        // as internet connection will be available.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, true);
        ed.apply();
        return;
    }

    final String cerNum = sp.getString(MainActivity.CER_NUMBER, MainActivity.EMPTY_STRING);
    final String regNum = sp.getString(MainActivity.REG_NUMBER, MainActivity.EMPTY_STRING);
    final boolean login = sp.getBoolean(MainActivity.AUTO_LOGIN, false);
    if (!login) { // If no auto login user detected.
        Logger.debug("AlarmReceiver", "Why we enter this case if no auto login users detected?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        return;
    }

    if (TextUtils.isEmpty(cerNum) || TextUtils.isEmpty(regNum)) {
        Logger.debug("AlarmReceiver", "Why we enter this case if both data are null or empty?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        // Remove auto login.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.AUTO_LOGIN, false);
        ed.apply();
        return;
    }

    // Start downloading data from internet.
    Submitter submitter = new Submitter(cerNum, regNum, this);
    submitter.executeOnExecutor(Executors.newSingleThreadExecutor());
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//www .j av  a  2s .  co  m
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}