Example usage for android.content Context sendBroadcast

List of usage examples for android.content Context sendBroadcast

Introduction

In this page you can find the example usage for android.content Context sendBroadcast.

Prototype

public abstract void sendBroadcast(@RequiresPermission Intent intent);

Source Link

Document

Broadcast the given intent to all interested BroadcastReceivers.

Usage

From source file:edu.princeton.jrpalmer.asmlibrary.Settings.java

@Override
protected void onResume() {

    if (Util.trafficCop(this))
        finish();/*from   w  w w  .j a v  a  2 s .c  o  m*/
    IntentFilter uploadFilter;
    uploadFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_UPLOADED);
    uploadReceiver = new UploadReceiver();
    registerReceiver(uploadReceiver, uploadFilter);

    IntentFilter fixFilter;
    fixFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED);
    fixReceiver = new FixReceiver();
    registerReceiver(fixReceiver, fixFilter);

    shareMyData = PropertyHolder.getShareData();

    toggleParticipationViews(shareMyData);

    int nUploads = PropertyHolder.getNUploads();

    final long participationTime = PropertyHolder.ptCheck();
    participationTimeText.setBase(SystemClock.elapsedRealtime() - participationTime);

    // service button
    boolean isServiceOn = PropertyHolder.isServiceOn();

    mServiceButton.setChecked(isServiceOn);
    mServiceButton.setOnClickListener(new ToggleButton.OnClickListener() {
        public void onClick(View view) {
            if (view.getId() != R.id.service_button)
                return;
            Context context = view.getContext();
            boolean on = ((ToggleButton) view).isChecked();
            String schedule = on ? Util.MESSAGE_SCHEDULE : Util.MESSAGE_UNSCHEDULE;
            // Log.e(TAG, schedule + on);

            // now schedule or unschedule
            Intent intent = new Intent(getString(R.string.internal_message_id) + schedule);
            context.sendBroadcast(intent);
            showSpinner(on, storeMyData);

            if (on && shareMyData) {
                final long ptNow = PropertyHolder.ptStart();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.start();

                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                        "on," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));
            } else {

                final long ptNow = PropertyHolder.ptStop();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.stop();
                // stop uploader
                Intent stopUploaderIntent = new Intent(Settings.this, FileUploader.class);
                // Stop service if it is currently running
                stopService(stopUploaderIntent);

                if (shareMyData) {

                    ContentResolver ucr = getContentResolver();

                    ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                            "off," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));

                }

            }
            // If user turns CountdownDisplay on but GPS is not on, remind
            // user to turn
            // GPS on
            if (on) {
                final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                        buildAlertMessageNoGpsNoNet();
                    } else
                        buildAlertMessageNoGps();
                }
            }

            return;
        }
    });

    // interval spinner
    int intspinner_item = android.R.layout.simple_spinner_item;
    int dropdown_item = android.R.layout.simple_spinner_dropdown_item;
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.interval_array,
            intspinner_item);
    adapter.setDropDownViewResource(dropdown_item);
    mIntervalSpinner.setAdapter(adapter);
    mIntervalSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_interval)
                return;
            if (pos > mInterval.length)
                return;
            if (!PropertyHolder.isServiceOn()) {
                PropertyHolder.setAlarmInterval(mInterval[pos]);
                return;
            }
            PropertyHolder.setAlarmInterval(mInterval[pos]);
            mServiceButton.setChecked(true);

            Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE);
            Context context = getApplicationContext();
            context.sendBroadcast(intent);
            showSpinner(true, storeMyData);

            if (shareMyData) {
                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("INT",
                        Util.iso8601(System.currentTimeMillis()) + "," + mInterval[pos]));
            }
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int pos = ai2pos(PropertyHolder.getAlarmInterval());
    mIntervalSpinner.setSelection(pos);
    showSpinner(isServiceOn, storeMyData);

    // mydata buttons

    // storage spinner

    storageDays = PropertyHolder.getStorageDays();

    mStorageSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_mydata)
                return;
            if (pos > MAX_STORAGE - MIN_STORAGE)
                return;
            PropertyHolder.setStorageDays(pos + MIN_STORAGE);
            PropertyHolder.setStoreMyData((pos + MIN_STORAGE) > 0);
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int storagepos = storageDays - MIN_STORAGE;
    mStorageSpinner.setSelection(storagepos);

    // NEW STUFF
    mToggleSatRadioGroup = (RadioGroup) findViewById(R.id.toggleSatRadioGroup);
    mToggleIconsRadioGroup = (RadioGroup) findViewById(R.id.toggleIconsRadioGroup);
    mToggleAccRadioGroup = (RadioGroup) findViewById(R.id.toggleAccRadioGroup);
    mLimitStartDateRadioGroup = (RadioGroup) findViewById(R.id.limitStartDateRadioGroup);
    mLimitEndDateRadioGroup = (RadioGroup) findViewById(R.id.limitEndDateRadioGroup);

    Intent i = getIntent();
    if (i.getBooleanExtra(MapMyData.DATES_BUTTON_MESSAGE, false)) {

        RelativeLayout dateSettingsArea = (RelativeLayout) findViewById(R.id.dateSettingsArea);
        dateSettingsArea.setFocusable(true);
        dateSettingsArea.setFocusableInTouchMode(true);
        dateSettingsArea.requestFocus();
    }

    if (shareMyData && isServiceOn) {
        participationTimeText.setBase(SystemClock.elapsedRealtime() - PropertyHolder.ptStart());
        participationTimeText.start();
    }

    nUploadsText.setText(String.valueOf(nUploads));

    if (nUploads >= Util.UPLOADS_TO_PRO && !PropertyHolder.getProVersion()
            && participationTime >= Util.TIME_TO_PRO) {
        Util.createProNotification(context);
        PropertyHolder.setProVersion(true);
        PropertyHolder.setNeedsDebriefingSurvey(true);
    }

    boolean proV = PropertyHolder.getProVersion();

    // 19 December 2013: end of research changes
    mShareDataRadioGroup.check(R.id.sharedataNo);

    mShareDataRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.sharedataYes) {
                buildSharingOverAnnouncement();
            }
            mShareDataRadioGroup.check(R.id.sharedataNo);
        }
    });

    /*
     * if (proV) {
     * 
     * if (shareMyData) { mShareDataRadioGroup.check(R.id.sharedataYes); if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context); } }
     * else { mShareDataRadioGroup.check(R.id.sharedataNo); }
     * 
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { shareMyData = (checkedId == R.id.sharedataYes);
     * PropertyHolder.setShareData(shareMyData);
     * toggleParticipationViews(shareMyData); final boolean on =
     * PropertyHolder.isServiceOn(); if (shareMyData) { if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context);
     * 
     * } if (on) {
     * 
     * final long ptNow = PropertyHolder.ptStart();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow);
     * 
     * participationTimeText.start();
     * 
     * ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "on," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * } } else {
     * 
     * final long ptNow = PropertyHolder.ptStop();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow); participationTimeText.stop(); // stop uploader Intent i = new
     * Intent(Settings.this, FileUploader.class); // Stop service if it is
     * currently running stopService(i);
     * 
     * if (on) { ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "off," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * }
     * 
     * }
     * 
     * } }); } else { mShareDataRadioGroup.check(R.id.sharedataYes);
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { if (checkedId == R.id.sharedataNo) {
     * mShareDataRadioGroup.check(R.id.sharedataYes);
     * showCurrentlySharingDialog(); } } });
     * 
     * }
     */
    new CheckPendingUploadsSizeTask().execute(context);
    new CheckUserDbSizeTask().execute(context);

    deletePendingUploadsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getUploadQueueUri(context), "1", null);

            // Log.i("Settings", "number of rows deleted=" + nDeleted);
            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");

            updateStorageSizes();

        }

    });

    deleteUserDbButton = (ImageButton) findViewById(R.id.deleteMyDbButton);

    deleteUserDbButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getFixesUri(context), "1", null);

            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");
            updateStorageSizes();

        }

    });

    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Util.isOnline(context)) {
                Intent i = new Intent(Settings.this, FileUploader.class);
                startService(i);

                new UploadMessageTask().execute(context);
            } else {
                Util.toast(context, getResources().getString(R.string.offline_warning));
            }

        }

    });

    mToggleSatRadioGroup.check(PropertyHolder.getMapSat() ? R.id.toggleSatYes : R.id.toggleSatNo);

    mToggleSatRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapSat(checkedId == R.id.toggleSatYes);
        }
    });

    mToggleIconsRadioGroup.check(PropertyHolder.getMapIcons() ? R.id.toggleIconsYes : R.id.toggleIconsNo);

    mToggleIconsRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapIcons(checkedId == R.id.toggleIconsYes);
        }
    });

    mToggleAccRadioGroup.check(PropertyHolder.getMapAcc() ? R.id.toggleAccYes : R.id.toggleAccNo);

    mToggleAccRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapAcc(checkedId == R.id.toggleAccYes);
        }
    });

    mStartDateButton = (Button) findViewById(R.id.startDateButton);
    mEndDateButton = (Button) findViewById(R.id.endDateButton);

    boolean limitStartDate = PropertyHolder.getLimitStartDate();
    boolean limitEndDate = PropertyHolder.getLimitEndDate();

    if (!limitStartDate)
        mStartDateButton.setVisibility(View.GONE);
    else {
        mStartDateButton.setVisibility(View.VISIBLE);

    }
    if (!limitEndDate)
        mEndDateButton.setVisibility(View.GONE);
    else {
        mEndDateButton.setVisibility(View.VISIBLE);
    }

    mLimitStartDateRadioGroup.check(limitStartDate ? R.id.limitStartDateYes : R.id.limitStartDateNo);

    mLimitStartDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitStartDate(checkedId == R.id.limitStartDateYes);

            if (checkedId != R.id.limitStartDateYes)
                mStartDateButton.setVisibility(View.GONE);
            else {
                mStartDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mLimitEndDateRadioGroup.check(limitEndDate ? R.id.limitEndDateYes : R.id.limitEndDateNo);

    mLimitEndDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitEndDate(checkedId == R.id.limitEndDateYes);

            if (checkedId != R.id.limitEndDateYes)
                mEndDateButton.setVisibility(View.GONE);
            else {
                mEndDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mStartDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapStartDate()));
    mStartDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new StartDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    mEndDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapEndDate()));
    mEndDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new EndDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    if (PropertyHolder.getNeedsDebriefingSurvey()) {
        buildProAnnouncement();
        PropertyHolder.setNeedsDebriefingSurvey(false);
    }

    super.onResume();

}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

private void sendQoSDisconnectErrorIntent(int error, String errorText) {
    Intent intent = new Intent("org.mobicents.restcomm.android.DISCONNECT_ERROR");
    intent.putExtra("STATE", "disconnect error");
    if (errorText != null)
        intent.putExtra("ERRORTEXT", errorText);
    intent.putExtra("ERROR", error);
    intent.putExtra("INCOMING", this.isIncoming());

    Context context = RCClient.getContext();
    try {/*from   w  w  w  .j  ava  2s.co  m*/
        // Restrict the Intent to MMC Handler running within the same application
        Class aclass = Class.forName("com.cortxt.app.corelib.Services.Intents.IntentHandler");
        intent.setClass(context.getApplicationContext(), aclass);
        context.sendBroadcast(intent);
    } catch (ClassNotFoundException e) {
        // If the MMC class isn't here, no intent
    }
}

From source file:org.mobicents.restcomm.android.client.sdk.RCConnection.java

private void sendQoSConnectionIntent(String state) {
    SignalingParameters params = this.signalingParameters;
    Intent intent = new Intent("org.mobicents.restcomm.android.CALL_STATE");

    intent.putExtra("STATE", state);
    intent.putExtra("INCOMING", this.isIncoming());
    if (params != null) {
        intent.putExtra("VIDEO", params.videoEnabled);
        intent.putExtra("REQUEST", params.sipUrl);
    }//  w  w w . j a v  a2s  . co m
    if (this.getState() != null)
        intent.putExtra("CONNECTIONSTATE", this.getState().toString());

    Context context = RCClient.getContext();
    try {
        // Restrict the Intent to MMC Handler running within the same application
        Class aclass = Class.forName("com.cortxt.app.corelib.Services.Intents.IntentHandler");
        intent.setClass(context.getApplicationContext(), aclass);
        context.sendBroadcast(intent);
    } catch (ClassNotFoundException e) {
        // If the MMC class isn't here, no intent
    }
}

From source file:com.zzl.zl_app.cache.Utility.java

public static boolean loadFile(String loadpath, String fileName, String savePath, Context context,
        String broadcastAction) {
    FileOutputStream fos = null; // ?
    FileInputStream fis = null; // ?
    InputStream is = null; // ?
    HttpURLConnection httpConnection = null;
    int readLength = 0; // ??
    int file_length = 0;
    URL url = null;/*from   w  w w.j a v a 2  s .  c  o m*/
    try {
        url = new URL(loadpath);
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(10000);
        httpConnection.setRequestMethod("GET");
        is = httpConnection.getInputStream();
        FileTools.creatDir(savePath);
        String filePath = savePath + fileName;
        FileTools.deleteFile(filePath);
        FileTools.creatFile(filePath);
        File download_file = new File(filePath);
        fos = new FileOutputStream(download_file, true); // ??
        fis = new FileInputStream(download_file); // ??
        int total_read = fis.available(); // ??0
        file_length = httpConnection.getContentLength(); // ?
        if (is == null) { // ?
            Tools.log("Voice", "donload failed...");
            return false;
        }
        byte buf[] = new byte[3072]; // 
        readLength = 0; // 
        Tools.log("Voice", "download start...");
        Intent startIntent = new Intent();
        Bundle b = new Bundle();
        if (broadcastAction != null) {
            // ?????
            b.putInt("fileSize", file_length);
            b.putInt("progress", 0);
            startIntent.putExtras(b);
            startIntent.setAction(broadcastAction);
            context.sendBroadcast(startIntent);
        }
        // ?????
        while (readLength != -1) {
            if ((readLength = is.read(buf)) > 0) {
                fos.write(buf, 0, readLength);
                total_read += readLength; // 
            }
            if (broadcastAction != null) {
                b.putInt("fileSize", file_length);
                b.putInt("progress", total_read);
                startIntent.putExtras(b);
                startIntent.setAction(broadcastAction);
                context.sendBroadcast(startIntent);
            }
            if (total_read == file_length) { // ?
                Tools.log("Voice", "download complete...");
                // ??????
                if (broadcastAction != null) {
                    Intent completeIntent = new Intent();
                    b.putBoolean("isFinish", true);
                    completeIntent.putExtras(b);
                    completeIntent.setAction(broadcastAction);
                    context.sendBroadcast(completeIntent);
                }

            }
            // Thread.sleep(10); // ?10
        }
    } catch (Exception e) {
        if (broadcastAction != null) {
            Intent errorIntent = new Intent();
            errorIntent.setAction(broadcastAction);
            context.sendBroadcast(errorIntent);
            e.printStackTrace();
        }
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (fis != null) {
                is.close();
            }
            if (fis != null) {
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return true;
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendMmsMessage(String text, String[] addresses, Bitmap[] image, String[] imageNames, byte[] media,
        String mimeType, String subject) {
    // merge the string[] of addresses into a single string so they can be inserted into the database easier
    String address = "";

    for (int i = 0; i < addresses.length; i++) {
        address += addresses[i] + " ";
    }/*from  ww w.j  a  va 2s.c  om*/

    address = address.trim();

    // create the parts to send
    ArrayList<MMSPart> data = new ArrayList<>();

    for (int i = 0; i < image.length; i++) {
        // turn bitmap into byte array to be stored
        byte[] imageBytes = Message.bitmapToByteArray(image[i]);

        MMSPart part = new MMSPart();
        part.MimeType = "image/jpeg";
        part.Name = (imageNames != null) ? imageNames[i] : ("image" + i);
        part.Data = imageBytes;
        data.add(part);
    }

    // add any extra media according to their mimeType set in the message
    //      eg. videos, audio, contact cards, location maybe?
    if (media.length > 0 && mimeType != null) {
        MMSPart part = new MMSPart();
        part.MimeType = mimeType;
        part.Name = mimeType.split("/")[0];
        part.Data = media;
        data.add(part);
    }

    if (!text.equals("")) {
        // add text to the end of the part and send
        MMSPart part = new MMSPart();
        part.Name = "text";
        part.MimeType = "text/plain";
        part.Data = text.getBytes();
        data.add(part);
    }

    MessageInfo info;

    try {
        info = getBytes(context, saveMessage, address.split(" "), data.toArray(new MMSPart[data.size()]),
                subject);
    } catch (MmsException e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        MmsMessageSender sender = new MmsMessageSender(context, info.location, info.bytes.length);
        sender.sendMessage(info.token);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ProgressCallbackEntity.PROGRESS_STATUS_ACTION);
        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                int progress = intent.getIntExtra("progress", -3);
                if (LOCAL_LOGV)
                    Log.v(TAG, "progress: " + progress);

                // send progress broadcast to update ui if desired...
                Intent progressIntent = new Intent(MMS_PROGRESS);
                progressIntent.putExtra("progress", progress);
                context.sendBroadcast(progressIntent);

                if (progress == ProgressCallbackEntity.PROGRESS_COMPLETE) {
                    context.sendBroadcast(new Intent(REFRESH));

                    try {
                        context.unregisterReceiver(this);
                    } catch (Exception e) {
                        // TODO fix me
                        // receiver is not registered force close error... hmm.
                    }
                } else if (progress == ProgressCallbackEntity.PROGRESS_ABORT) {
                    // This seems to get called only after the progress has reached 100 and then something else goes wrong, so here we will try and send again and see if it works
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending aborted for some reason...");
                }
            }

        };

        context.registerReceiver(receiver, filter);
    } catch (Throwable e) {
        Log.e(TAG, "exception thrown", e);
        // insert the pdu into the database and return the bytes to send
        if (settings.getWifiMmsFix()) {
            sendMMS(info.bytes);
        } else {
            sendMMSWiFi(info.bytes);
        }
    }
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void trySending(final APN apns, final byte[] bytesToSend, final int numRetries) {
    try {/*from  ww w  .  j  a va  2 s .c om*/
        IntentFilter filter = new IntentFilter();
        filter.addAction(ProgressCallbackEntity.PROGRESS_STATUS_ACTION);
        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                int progress = intent.getIntExtra("progress", -3);
                if (LOCAL_LOGV)
                    Log.v(TAG, "progress: " + progress);

                // send progress broadcast to update ui if desired...
                Intent progressIntent = new Intent(MMS_PROGRESS);
                progressIntent.putExtra("progress", progress);
                context.sendBroadcast(progressIntent);

                if (progress == ProgressCallbackEntity.PROGRESS_COMPLETE) {
                    if (saveMessage) {
                        Cursor query = context.getContentResolver().query(Uri.parse("content://mms"),
                                new String[] { "_id" }, null, null, "date desc");
                        if (query != null && query.moveToFirst()) {
                            String id = query.getString(query.getColumnIndex("_id"));
                            query.close();

                            // move to the sent box
                            ContentValues values = new ContentValues();
                            values.put("msg_box", 2);
                            String where = "_id" + " = '" + id + "'";
                            context.getContentResolver().update(Uri.parse("content://mms"), values, where,
                                    null);
                        }
                    }

                    context.sendBroadcast(new Intent(REFRESH));

                    try {
                        context.unregisterReceiver(this);
                    } catch (Exception e) {
                        /* Receiver not registered */ }

                    // give everything time to finish up, may help the abort being shown after the progress is already 100
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mConnMgr.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE_MMS, "enableMMS");
                            if (settings.getWifiMmsFix()) {
                                reinstateWifi();
                            }
                        }
                    }, 1000);
                } else if (progress == ProgressCallbackEntity.PROGRESS_ABORT) {
                    // This seems to get called only after the progress has reached 100 and then something else goes wrong, so here we will try and send again and see if it works
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending aborted for some reason...");
                    context.unregisterReceiver(this);

                    if (numRetries < NUM_RETRIES) {
                        // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time
                        try {
                            Thread.sleep(3000);
                        } catch (Exception f) {

                        }

                        if (settings.getWifiMmsFix()) {
                            sendMMS(bytesToSend);
                        } else {
                            sendMMSWiFi(bytesToSend);
                        }
                    } else {
                        markMmsFailed();
                    }
                }
            }

        };

        context.registerReceiver(receiver, filter);

        // This is where the actual post request is made to send the bytes we previously created through the given apns
        if (LOCAL_LOGV)
            Log.v(TAG, "attempt: " + numRetries);
        Utils.ensureRouteToHost(context, apns.MMSCenterUrl, apns.MMSProxy);
        HttpUtils.httpConnection(context, 4444L, apns.MMSCenterUrl, bytesToSend, HttpUtils.HTTP_POST_METHOD,
                !TextUtils.isEmpty(apns.MMSProxy), apns.MMSProxy, Integer.parseInt(apns.MMSPort));
    } catch (IOException e) {
        if (LOCAL_LOGV)
            Log.v(TAG, "some type of error happened when actually sending maybe?");
        Log.e(TAG, "exception thrown", e);

        if (numRetries < NUM_RETRIES) {
            // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time
            try {
                Thread.sleep(3000);
            } catch (Exception f) {

            }

            trySending(apns, bytesToSend, numRetries + 1);
        } else {
            markMmsFailed();
        }
    }
}

From source file:org.wso2.iot.agent.events.listeners.ApplicationStateListener.java

@Override
public void onReceive(Context context, final Intent intent) {
    String status = null;/*w  w  w . j  a va 2 s.  c o m*/
    ApplicationStatus applicationState;
    this.context = context;
    switch (intent.getAction()) {
    case Intent.ACTION_PACKAGE_ADDED:
        status = "added";
        applyEnforcement(intent.getData().getEncodedSchemeSpecificPart());
        break;
    case Intent.ACTION_PACKAGE_REMOVED:
        status = "removed";
        break;
    case Intent.ACTION_PACKAGE_REPLACED:
        status = "upgraded";
        break;
    case Intent.ACTION_PACKAGE_DATA_CLEARED:
        status = "dataCleared";
        break;
    default:
        Log.i(TAG, "Invalid intent received");
    }
    if (status != null) {
        String packageName = intent.getData().getEncodedSchemeSpecificPart();
        applicationState = new ApplicationStatus();
        applicationState.setState(status);
        applicationState.setPackageName(packageName);
        try {
            String appState = CommonUtils.toJSON(applicationState);
            publishEvent(appState, Constants.EventListeners.APPLICATION_STATE);
            if (Constants.DEBUG_MODE_ENABLED) {
                Log.d(TAG, appState);
            }
        } catch (AndroidAgentException e) {
            Log.e(TAG, "Could not convert to JSON");
        }
        if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())
                && Constants.AGENT_PACKAGE.equals(packageName)) {
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(Constants.AGENT_UPDATED_BROADCAST_ACTION);
            context.sendBroadcast(broadcastIntent);
        }
    }
}

From source file:org.linuxac.bilal.BilalAlarm.java

@Override
public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra(BilalActivity.NOTIFY_MESSAGE);

    Log.d(BilalActivity.TAG, "Alarm is ON: " + message);

    // Play athan
    Intent audioIntent = new Intent(context, AthanAudio.class);
    context.startService(audioIntent);//w ww .  ja v  a 2 s  . c om

    // Build intent for notification content
    int notificationId = 0;
    int eventId = 0;
    Intent nextPrayerIntent = new Intent(context, BilalActivity.class);
    nextPrayerIntent.putExtra(EXTRA_EVENT_ID, eventId);
    PendingIntent nextPrayerPendingIntent = PendingIntent.getActivity(context, 0, nextPrayerIntent, 0);

    // Use another intent to stop athan from notification button
    PendingIntent cancelAthanPendingIntent = CancelAthanActivity.getCancelAthanIntent(notificationId, context);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle(BilalActivity.TAG).setContentText(message)
            .setContentIntent(nextPrayerPendingIntent).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setAutoCancel(true).setDeleteIntent(cancelAthanPendingIntent)
            .addAction(R.drawable.ic_clear, "? ", cancelAthanPendingIntent);

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    // Build the notification and issues it with notification manager.
    notificationManager.notify(notificationId, notificationBuilder.build());

    // ask Activity to update display to next prayer. TODO: delay highlighting of next prayer
    Intent updateIntent = new Intent(BilalActivity.UPDATE_MESSAGE);
    context.sendBroadcast(updateIntent);
}

From source file:com.amaze.filemanager.utils.Futils.java

public void scanFile(String path, Context c) {
    System.out.println(path + " " + Build.VERSION.SDK_INT);
    if (Build.VERSION.SDK_INT >= 19) {
        MediaScannerConnection.scanFile(c, new String[] { path }, null,
                new MediaScannerConnection.OnScanCompletedListener() {

                    @Override/*from   w w w  .j a v a2s.co m*/
                    public void onScanCompleted(String path, Uri uri) {

                    }
                });
    } else {
        Uri contentUri = Uri.fromFile(new File(path));
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri);
        c.sendBroadcast(mediaScanIntent);
    }
}

From source file:com.openerp.services.MailGroupSyncService.java

public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    try {/* ww w . ja  v a 2  s. c o m*/
        Intent intent = new Intent();
        intent.setAction(SyncFinishReceiver.SYNC_FINISH);

        MailGroupDB db = new MailGroupDB(context);
        db.setAccountUser(OpenERPAccountManager.getAccountDetail(context, account.name));
        OEHelper oe = db.getOEInstance();
        if (oe != null && oe.syncWithServer(true)) {
            MailFollowers followers = new MailFollowers(context);

            OEDomain domain = new OEDomain();
            domain.add("partner_id", "=", oe.getUser().getPartner_id());
            domain.add("res_model", "=", db.getModelName());

            if (followers.getOEInstance().syncWithServer(domain, true)) {
                // syncing group messages
                JSONArray group_ids = new JSONArray();
                for (OEDataRow grp : followers.select("res_model = ? AND partner_id = ?",
                        new String[] { db.getModelName(), oe.getUser().getPartner_id() + "" })) {
                    group_ids.put(grp.getInt("res_id"));
                }
                Bundle messageBundle = new Bundle();
                messageBundle.putString("group_ids", group_ids.toString());
                messageBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                messageBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                ContentResolver.requestSync(account, MessageProvider.AUTHORITY, messageBundle);

            }
        }
        if (OpenERPAccountManager.currentUser(context).getAndroidName().equals(account.name))
            context.sendBroadcast(intent);

    } catch (Exception e) {
        e.printStackTrace();
    }
}