Example usage for android.content Context unregisterReceiver

List of usage examples for android.content Context unregisterReceiver

Introduction

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

Prototype

public abstract void unregisterReceiver(BroadcastReceiver receiver);

Source Link

Document

Unregister a previously registered BroadcastReceiver.

Usage

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] + " ";
    }/*  ww w  . ja  va  2 s  .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.marianhello.cordova.bgloc.BackgroundGpsPlugin.java

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    Activity activity = this.cordova.getActivity();
    Context context = activity.getApplicationContext();
    Boolean result = false;// w ww.ja v a 2 s.  c  o  m
    updateServiceIntent = new Intent(activity, LocationUpdateService.class);

    if (ACTION_START.equalsIgnoreCase(action) && !isEnabled) {
        result = true;
        if (params == null || headers == null) {
            callbackContext.error("Call configure before calling start");
        } else {
            IntentFilter intentFilter = new IntentFilter(Constant.FILTER);
            // LocalBroadcastManager.getInstance(activity).registerReceiver(mMessageReceiver, intentFilter);
            context.registerReceiver(mMessageReceiver, intentFilter);

            updateServiceIntent.putExtra("url", url);
            updateServiceIntent.putExtra("params", params);
            updateServiceIntent.putExtra("headers", headers);
            updateServiceIntent.putExtra("stationaryRadius", stationaryRadius);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("distanceFilter", distanceFilter);
            updateServiceIntent.putExtra("locationTimeout", locationTimeout);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("isDebugging", isDebugging);
            updateServiceIntent.putExtra("notificationTitle", notificationTitle);
            updateServiceIntent.putExtra("notificationText", notificationText);
            updateServiceIntent.putExtra("stopOnTerminate", stopOnTerminate);

            activity.startService(updateServiceIntent);
            isEnabled = true;
            Log.d(TAG, "bg service has been started");
        }
    } else if (ACTION_STOP.equalsIgnoreCase(action)) {
        // LocalBroadcastManager.getInstance(activity).unregisterReceiver(mMessageReceiver);
        context.unregisterReceiver(mMessageReceiver);

        isEnabled = false;
        result = true;
        activity.stopService(updateServiceIntent);
        callbackContext.success();
        Log.d(TAG, "bg service has been stopped");
    } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) {
        result = true;
        try {
            this.callbackContext = callbackContext;
            // Params.
            //    0       1       2           3               4                5               6            7           8                9               10              11
            //[params, headers, url, stationaryRadius, distanceFilter, locationTimeout, desiredAccuracy, debug, notificationTitle, notificationText, activityType, stopOnTerminate]
            this.params = data.getString(0);
            this.headers = data.getString(1);
            this.url = data.getString(2);
            this.stationaryRadius = data.getString(3);
            this.distanceFilter = data.getString(4);
            this.locationTimeout = data.getString(5);
            this.desiredAccuracy = data.getString(6);
            this.isDebugging = data.getString(7);
            this.notificationTitle = data.getString(8);
            this.notificationText = data.getString(9);
            this.stopOnTerminate = data.getString(11);
            Log.d(TAG, "bg service configured");
        } catch (JSONException e) {
            callbackContext.error("authToken/url required as parameters: " + e.getMessage());
        }
    } else if (ACTION_SET_CONFIG.equalsIgnoreCase(action)) {
        result = true;
        // TODO reconfigure Service
        callbackContext.success();
        Log.d(TAG, "bg service reconfigured");
    } else if (ACTION_LOCATION_ENABLED_CHECK.equalsIgnoreCase(action)) {
        Log.d(TAG, "location services enabled check");
        try {
            int isLocationEnabled = BackgroundGpsPlugin.isLocationEnabled(context) ? 1 : 0;
            callbackContext.success(isLocationEnabled);
        } catch (SettingNotFoundException e) {
            callbackContext.error("Location setting not found on this platform");
        }
    }

    return result;
}

From source file:xj.property.activity.HXBaseActivity.MainActivity.java

private void unregisterHomeKeyReceiver(Context context) {
    Log.i(TAG, "unregisterHomeKeyReceiver");
    if (null != mHomeKeyReceiver) {
        context.unregisterReceiver(mHomeKeyReceiver);
    }/* w ww  . jav  a2s  .  c om*/
}

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 v a  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:RhodesService.java

private File downloadPackage(String url) throws IOException {
    final Context ctx = RhodesActivity.getContext();

    final Thread thisThread = Thread.currentThread();

    final Runnable cancelAction = new Runnable() {
        public void run() {
            thisThread.interrupt();//from   w w w.  j  a v  a 2s .  com
        }
    };

    BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setMessage("Cancel download?");
                AlertDialog dialog = builder.create();
                dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                cancelAction.run();
                            }
                        });
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Nothing
                            }
                        });
                dialog.show();
            } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) {
                cancelAction.run();
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD);
    filter.addAction(ACTION_CANCEL_DOWNLOAD);
    ctx.registerReceiver(downloadReceiver, filter);

    File tmpFile = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        updateDownloadNotification(url, -1, 0);

        /*
        List<File> folders = new ArrayList<File>();
        folders.add(Environment.getDownloadCacheDirectory());
        folders.add(Environment.getDataDirectory());
        folders.add(ctx.getCacheDir());
        folders.add(ctx.getFilesDir());
        try {
           folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir));
        } catch (NameNotFoundException e1) {
           // Ignore
        }
        folders.add(Environment.getExternalStorageDirectory());
                
        for (File folder : folders) {
           File tmpRootFolder = new File(folder, "rhodownload");
           File tmpFolder = new File(tmpRootFolder, ctx.getPackageName());
           if (tmpFolder.exists())
              deleteFilesInFolder(tmpFolder.getAbsolutePath());
           else
              tmpFolder.mkdirs();
                   
           File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk");
           Logger.D(TAG, "Check path " + of.getAbsolutePath() + "...");
           try {
              os = new FileOutputStream(of);
           }
           catch (FileNotFoundException e) {
              Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path");
              continue;
           }
           Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app");
                   
           tmpFile = of;
           break;
        }
        */

        tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk");
        os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE);

        Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "...");

        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int totalBytes = -1;
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            totalBytes = httpConn.getContentLength();
        }
        is = conn.getInputStream();

        int downloaded = 0;
        updateDownloadNotification(url, totalBytes, downloaded);

        long prevProgress = 0;
        byte[] buf = new byte[65536];
        for (;;) {
            if (thisThread.isInterrupted()) {
                tmpFile.delete();
                Logger.D(TAG, "Download of " + url + " was canceled");
                return null;
            }
            int nread = is.read(buf);
            if (nread == -1)
                break;

            //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes...");
            os.write(buf, 0, nread);

            downloaded += nread;
            if (totalBytes > 0) {
                // Update progress view only if current progress is greater than
                // previous by more than 10%. Otherwise, if update it very frequently,
                // user will no have chance to click on notification view and cancel if need
                long progress = downloaded * 10 / totalBytes;
                if (progress > prevProgress) {
                    updateDownloadNotification(url, totalBytes, downloaded);
                    prevProgress = progress;
                }
            }
        }

        Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath());

        return tmpFile;
    } catch (IOException e) {
        if (tmpFile != null)
            tmpFile.delete();
        throw e;
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }

        mNM.cancel(DOWNLOAD_PACKAGE_ID);
        ctx.unregisterReceiver(downloadReceiver);
    }
}