Example usage for android.app PendingIntent getBroadcast

List of usage examples for android.app PendingIntent getBroadcast

Introduction

In this page you can find the example usage for android.app PendingIntent getBroadcast.

Prototype

public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) Context.sendBroadcast() .

Usage

From source file:com.footprint.cordova.plugin.localnotification.LocalNotification.java

/**
 * Set an alarm./*from   w ww .  j  a  v  a2 s. c  o m*/
 *
 * @param options
 *            The options that can be specified per alarm.
 * @param doFireEvent
 *            If the onadd callback shall be called.
 */
public static void add(Options options, boolean doFireEvent) {
    long triggerTime = options.getDate();

    Intent intent = new Intent(context, Receiver.class).setAction("" + options.getId())
            .putExtra(Receiver.OPTIONS, options.getJSONObject().toString());

    AlarmManager am = getAlarmManager();
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    if (doFireEvent) {
        fireEvent("add", options.getId(), options.getJSON());
    }

    am.set(AlarmManager.RTC_WAKEUP, triggerTime, pi);
}

From source file:co.carlosandresjimenez.android.gotit.notification.AlarmReceiver.java

/**
 * Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the
 * alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver.
 *
 * @param context//  w ww . j a  va  2s  .c  om
 */
public void setAlarm(Context context) {

    // If the alarm has been set, cancel it.
    if (alarmMgr != null) {
        alarmIntent.cancel();
        alarmMgr.cancel(alarmIntent);
    }

    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    int userFrequencySetting = Utility.getNotificationFrequency(context);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.HOUR, userFrequencySetting);

    // Set the alarm to fire in X hours according to the device's
    // clock and user settings, and to repeat according to user settings
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            userFrequencySetting * ONE_HOUR_MILLISECONDS, alarmIntent);

    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();

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

From source file:com.appsaur.tarucassist.AutomuteAlarmReceiver.java

public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
    mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    // Put Reminder ID in Intent Extra
    Intent intent = new Intent(context, AutomuteAlarmReceiver.class);
    intent.putExtra(BaseActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
    mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Calculate notification timein
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();
    long diffTime = calendar.getTimeInMillis() - currentTime;

    // Start alarm using initial notification time and repeat interval time
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + diffTime,
            RepeatTime, mPendingIntent);

    // Restart alarm if device is rebooted
    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
}

From source file:com.google.android.example.basicawarenesssample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);// w  ww . j a  v a 2  s .  c  o m

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            printSnapshot();
        }
    });

    Context context = this;
    mApiClient = new GoogleApiClient.Builder(context).addApi(Awareness.API).enableAutoManage(this, 1, null)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    // Set up the PendingIntent that will be fired when the fence is triggered.
                    Intent intent = new Intent(FENCE_RECEIVER_ACTION);
                    mPendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);

                    // The broadcast receiver that will receive intents when a fence is triggered.
                    mFenceReceiver = new FenceReceiver();
                    registerReceiver(mFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));
                    setupFences();
                }

                @Override
                public void onConnectionSuspended(int i) {
                }
            }).build();
    mLogFragment = (LogFragment) getSupportFragmentManager().findFragmentById(R.id.log_fragment);
}

From source file:com.cliqz.browser.gcm.MessageListenerService.java

/**
 * Create and show a simple notification containing the received GCM message. Does nothing if
 * the notifications are disabled in the preferences.
 *
 * @param title GCM message received./*from w w  w .ja  v  a 2 s .c o  m*/
 * @param url   url
 */
private void sendNewsNotification(int newType, String title, String url, String country) {
    if (!preferenceManager.getNewsNotificationEnabled() || country == null
            || !country.equals(preferenceManager.getCountryChoice().countryCode)) {
        return;
    }

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.putExtra(Constants.NOTIFICATION_CLICKED, true);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Intent deleteIntent = new Intent(this, NotificationDismissedReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0,
            deleteIntent, 0);

    final Uri uri = Uri.parse(url);
    final String host = uri.getHost();
    final String domain = UrlUtils.getTopDomain(url);
    final Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    final NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
    style.bigText(title);
    final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification_news).setContentTitle(domain)
            .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION).setContentText(title).setAutoCancel(true)
            .setSound(defaultSoundUri).setContentIntent(pendingIntent).setDeleteIntent(deletePendingIntent)
            .setStyle(style);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

From source file:com.andrewquitmeyer.MarkYourTerritory.DemoKitActivity.java

/** Called when the activity is first created. */
@Override/* w  w  w  . j  a  v  a 2s. c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUsbManager = UsbManager.getInstance(this);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    if (getLastNonConfigurationInstance() != null) {
        mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
        openAccessory(mAccessory);
    }

    setContentView(R.layout.maintwo);
    nodeviceview = (View) findViewById(R.id.noDevice);

    enableControls(false);
}

From source file:com.bobomee.android.common.util.NotificationUtil.java

public static NotificationCompat.Builder setBroadCastIntent(NotificationCompat.Builder mBuilder,
        Context context, Intent intent) {
    // ?ACTIONIntent
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingIntent);
    return mBuilder;
}

From source file:com.jigarmjoshi.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (SimpleDatabaseUtil.isFirstApplicationStart(this)) {
        Log.i(MainActivity.class.getSimpleName(), "creating database for the first time");
        SQLiteSimple databaseSimple = new SQLiteSimple(this, DATABASE_VERSION);
        databaseSimple.create(Report.class, LastLocation.class);
    } else if (SimpleDatabaseUtil.isFirstStartOnAppVersion(this, DATABASE_VERSION)) {
        Log.i(MainActivity.class.getSimpleName(),
                "creating database for the first time for this version " + DATABASE_VERSION);

        SQLiteSimple databaseSimple = new SQLiteSimple(this, DATABASE_VERSION);
        databaseSimple.create(Report.class, LastLocation.class);

    }//from  w w  w  .  j  ava 2 s.co  m
    // initialize services
    EntryDao.getInstance(this);
    LastLocationDao.getInstance(this);

    // scheduler
    mgr = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent i = new Intent(this, LocationPoller.class);
    com.jigarmjoshi.service.LocationManager locationManager = com.jigarmjoshi.service.LocationManager
            .getInstance(getApplicationContext());
    List<String> providers = locationManager.getAllProviders();
    boolean fusedSupported = false;
    for (String provider : providers) {
        if (com.jigarmjoshi.service.LocationManager.FUSED_PROVIDER.equals(provider)) {
            fusedSupported = true;
            break;
        }
    }
    i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(this, com.jigarmjoshi.reciever.LocationReceiver.class));
    i.putExtra(LocationPoller.EXTRA_PROVIDER,
            (fusedSupported ? LocationManager.FUSED_PROVIDER : LocationManager.GPS_PROVIDER));

    pi = PendingIntent.getBroadcast(this, 0, i, 0);
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
            Long.parseLong(ConfigService.get(ConfigService.GPS_TASK_INTERVAL, "40000")), pi);

    // upload task
    Timer timer = new Timer();
    TimerTask timerTask = new UploaderTask(this);
    timer.schedule(timerTask, 0,
            Long.parseLong(ConfigService.get(ConfigService.UPLOAD_TASK_INTERVAL, "40000")));

    selectedTextView = new TextView(this);
    selectedTextView.setTextColor(Color.BLACK);
    selectedTextView.setGravity(Gravity.CENTER);
    selectedTextView.setPaintFlags(Paint.FAKE_BOLD_TEXT_FLAG);

    unSelectedTextView = new TextView(this);
    unSelectedTextView.setTextColor(Color.GRAY);
    unSelectedTextView.setGravity(Gravity.CENTER);
    unSelectedTextView.setPaintFlags(Paint.FAKE_BOLD_TEXT_FLAG);
    // create if first time

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    actionBar = getActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#40808080")));
    actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#40808080")));
    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    boolean first = false;
    for (String tab_name : tabs) {
        Tab tab = actionBar.newTab().setText(tab_name).setTabListener(this);
        if (first) {
            first = false;
            selectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
            tab.setCustomView(selectedTextView);
        } else {
            unSelectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
            tab.setCustomView(unSelectedTextView);
        }
        actionBar.addTab(tab);
    }

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
    Toast.makeText(this, getString(R.string.wait_gps), Toast.LENGTH_LONG).show();
}

From source file:de.appplant.cordova.plugin.notification.Builder.java

/**
 * Set intent to handle the delete event. Will clean up some persisted
 * preferences.//  w w  w. j av  a 2s  .c  o  m
 *
 * @param builder
 *      Local notification builder instance
 */
private void applyDeleteReceiver(NotificationCompat.Builder builder) {

    if (clearReceiver == null)
        return;

    Intent deleteIntent = new Intent(context, clearReceiver).setAction(options.getId()).putExtra(Options.EXTRA,
            options.toString());

    PendingIntent dpi = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    builder.setDeleteIntent(dpi);
}

From source file:com.android.mms.transaction.SendTransaction.java

public void run() {
    Log.d(MmsApp.TXN_TAG, "SendTransaction: run");
    RateController rateCtlr = RateController.getInstance();
    if (rateCtlr.isLimitSurpassed() && !rateCtlr.isAllowedByUser()) {
        Log.e(TAG, "Sending rate limit surpassed.");
        return;/*ww  w  .j  a  v a  2  s  .com*/
    }

    try {
        final PduPersister persister = PduPersister.getPduPersister(mContext);
        final SendReq sendReq = (SendReq) persister.load(mUri);
        if (sendReq == null) {
            Log.w(MmsApp.TXN_TAG, "Send req is null!");
            return;
        }
        byte[] datas = new PduComposer(mContext, sendReq).make();
        mPduFile = createPduFile(datas, SEND_REQ_NAME + mUri.getLastPathSegment());
        if (mPduFile == null) {
            Log.w(MmsApp.TXN_TAG, "create pdu file req failed!");
            return;
        }

        //Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED);
        //intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);
        //intent.putExtra(TransactionBundle.URI, mUri.toString());
        Log.d(MmsApp.TXN_TAG, "SendTransaction mUri:" + mUri);
        final Intent intent = new Intent(TransactionService.ACTION_TRANSACION_PROCESSED, mUri, mContext,
                MmsReceiver.class);
        intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, mSubId);

        PendingIntent sentIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Log.d(MmsApp.TXN_TAG,
                "send MMS with param, mUri = " + mUri + " mPdufile = " + mPduFile + ", subId = " + mSubId);
        Uri pduFileUri = FileProvider.getUriForFile(mContext, MMS_FILE_PROVIDER_AUTHORITIES, mPduFile);
        /// M: Add MmsService configure param @{
        SmsManager.getSmsManagerForSubscriptionId(mSubId).sendMultimediaMessage(mContext, pduFileUri, null,
                MmsConfig.getMmsServiceConfig(), sentIntent);
        /// @}
    } catch (Throwable t) {
        Log.e(TAG, Log.getStackTraceString(t));
        getState().setState(FAILED);
        getState().setContentUri(mUri);
        notifyObservers();
    }
}