Example usage for android.content Intent getAction

List of usage examples for android.content Intent getAction

Introduction

In this page you can find the example usage for android.content Intent getAction.

Prototype

public @Nullable String getAction() 

Source Link

Document

Retrieve the general action to be performed, such as #ACTION_VIEW .

Usage

From source file:net.oschina.app.v2.activity.zxing.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();
    // historyManager must be initialized here to update the history preference
    // historyManager = new HistoryManager(this);
    // historyManager.trimHistory();

    // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
    // want to open the camera driver and measure the screen size if we're going to show the help on
    // first launch. That led to bugs where the scanning rectangle was the wrong size and partially
    // off screen.
    cameraManager = new CameraManager(getApplication());

    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);

    resultView = findViewById(R.id.result_view);
    statusView = (TextView) findViewById(R.id.status_view);

    handler = null;/*from w w  w  .j a v  a  2  s . c  o m*/
    lastResult = null;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_AUTO_ORIENTATION, true)) {
        //setRequestedOrientation(getCurrentOrientation());
    } else {
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }

    resetStatusView();

    beepManager.updatePrefs();
    ambientLightManager.start(cameraManager);

    inactivityTimer.onResume();

    Intent intent = getIntent();

    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
            && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));

    source = IntentSource.NONE;
    sourceUrl = null;
    scanFromWebPageManager = null;
    decodeFormats = null;
    characterSet = null;

    if (intent != null) {
        String action = intent.getAction();
        String dataString = intent.getDataString();

        if (Intents.Scan.ACTION.equals(action)) {

            // Scan the formats the intent requested, and return the result to the calling activity.
            source = IntentSource.NATIVE_APP_INTENT;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
            decodeHints = DecodeHintManager.parseDecodeHints(intent);

            if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                if (width > 0 && height > 0) {
                    cameraManager.setManualFramingRect(width, height);
                }
            }

            if (intent.hasExtra(Intents.Scan.CAMERA_ID)) {
                int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID, -1);
                if (cameraId >= 0) {
                    cameraManager.setManualCameraId(cameraId);
                }
            }

            String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
            if (customPromptMessage != null) {
                statusView.setText(customPromptMessage);
            }

        } else if (dataString != null && dataString.contains("http://www.google")
                && dataString.contains("/m/products/scan")) {

            // Scan only products and send the result to mobile Product Search.
            source = IntentSource.PRODUCT_SEARCH_LINK;
            sourceUrl = dataString;
            decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;

        } else if (isZXingURL(dataString)) {

            // Scan formats requested in query string (all formats if none specified).
            // If a return URL is specified, send the results there. Otherwise, handle it ourselves.
            source = IntentSource.ZXING_LINK;
            sourceUrl = dataString;
            Uri inputUri = Uri.parse(dataString);
            scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
            decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
            // Allow a sub-set of the hints to be specified by the caller.
            decodeHints = DecodeHintManager.parseDecodeHints(inputUri);

        }

        characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
    }

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the camera.
        surfaceHolder.addCallback(this);
    }
}

From source file:com.mobilyzer.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("MeasurementScheduler -> onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());

    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();

    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.mainQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.waitingTasksQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new WaitingTasksComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult[]>>();
    this.tasksStatus = new ConcurrentHashMap<String, MeasurementScheduler.TaskStatus>();
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    this.serverTasks = new HashMap<String, Date>();
    // this.currentSchedule = new HashMap<String, MeasurementTask>();

    this.idToClientKey = new ConcurrentHashMap<String, String>();

    messenger = new Messenger(new APIRequestHandler(this));

    gcmManager = new GCMManager(this.getApplicationContext());

    this.setCurrentTask(null);
    this.setCurrentTaskStartTime(null);

    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.batteryThreshold = -1;
    this.checkinIntervalSec = -1;
    this.dataUsageProfile = DataUsageProfile.NOTASSIGNED;

    //    loadSchedulerState();//TODO(ASHKAN)

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
    filter.addAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.PLT_MEASUREMENT_ACTION);

    broadcastReceiver = new BroadcastReceiver() {

        @Override//w w w . j  a v  a  2s.c o  m
        public void onReceive(Context context, Intent intent) {
            Logger.d(intent.getAction() + " RECEIVED");
            if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)) {
                handleMeasurement();

            } else if (intent.getAction().equals(UpdateIntent.GCM_MEASUREMENT_ACTION)) {
                try {
                    JSONObject json = new JSONObject(
                            intent.getExtras().getString(UpdateIntent.MEASUREMENT_TASK_PAYLOAD));
                    Logger.d("MeasurementScheduler -> GCMManager: json task Value is " + json);
                    if (json != null && MeasurementTask.getMeasurementTypes().contains(json.get("type"))) {

                        try {
                            MeasurementTask task = MeasurementJsonConvertor.makeMeasurementTaskFromJson(json);
                            task.getDescription().priority = MeasurementTask.GCM_PRIORITY;
                            task.getDescription().startTime = new Date(System.currentTimeMillis() - 1000);
                            task.getDescription().endTime = new Date(System.currentTimeMillis() + (600 * 1000));
                            task.generateTaskID();
                            task.getDescription().key = Config.SERVER_TASK_CLIENT_KEY;
                            submitTask(task);
                        } catch (IllegalArgumentException e) {
                            Logger.w("MeasurementScheduler -> GCM : Could not create task from JSON: " + e);
                        }
                    }

                } catch (JSONException e) {
                    Logger.e(
                            "MeasurementSchedule -> GCMManager : Got exception during converting GCM json to MeasurementTask",
                            e);
                }

            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                String taskid = intent.getStringExtra(UpdateIntent.TASKID_PAYLOAD);
                String taskKey = intent.getStringExtra(UpdateIntent.CLIENTKEY_PAYLOAD);
                int priority = intent.getIntExtra(UpdateIntent.TASK_PRIORITY_PAYLOAD,
                        MeasurementTask.INVALID_PRIORITY);

                Logger.e(
                        intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD) + " " + taskid + " " + taskKey);
                if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_FINISHED)) {
                    tasksStatus.put(taskid, TaskStatus.FINISHED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);

                        for (Object obj : results) {
                            try {
                                MeasurementResult result = (MeasurementResult) obj;
                                /**
                                 * Nullify the additional parameters in MeasurmentDesc, or the results won't be
                                 * accepted by GAE server
                                 */
                                result.getMeasurementDesc().parameters = null;
                                String jsonResult = MeasurementJsonConvertor.encodeToJson(result).toString();
                                saveResultToFile(jsonResult);
                            } catch (JSONException e) {
                                Logger.e("Error converting results to json format", e);
                            }
                        }
                    }
                    handleMeasurement();
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_PAUSED)) {
                    tasksStatus.put(taskid, TaskStatus.PAUSED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STOPPED)) {
                    tasksStatus.put(taskid, TaskStatus.SCHEDULED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_CANCELED)) {
                    tasksStatus.put(taskid, TaskStatus.CANCELLED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);
                    }
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STARTED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_RESUMED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                }
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)) {
                Logger.d("Checkin intent received");
                handleCheckin();
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
}

From source file:com.commontime.plugin.LocationManager.java

private void initBluetoothListener() {

    //check access
    if (!hasBlueToothPermission()) {
        debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added");
        return;/*from  w w w  .j a  v a 2  s  .c o m*/
    }

    //check device support
    try {
        iBeaconManager.checkAvailability();
    } catch (Exception e) {
        //if device does not support iBeacons an error is thrown
        debugWarn("Cannot listen to Bluetooth service: " + e.getMessage());
        return;
    }

    if (broadcastReceiver != null) {
        debugWarn("Already listening to Bluetooth service, not adding again");
        return;
    }

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            // Only listen for Bluetooth server changes
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                        BluetoothAdapter.ERROR);

                debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to "
                        + getStateDescription(state));

                switch (state) {
                case BluetoothAdapter.ERROR:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined");
                    break;
                case BluetoothAdapter.STATE_OFF:
                case BluetoothAdapter.STATE_TURNING_OFF:
                    if (oldState == BluetoothAdapter.STATE_ON)
                        beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied");
                    break;
                case BluetoothAdapter.STATE_ON:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
                }
            }
        }

        private String getStateDescription(int state) {
            switch (state) {
            case BluetoothAdapter.ERROR:
                return "ERROR";
            case BluetoothAdapter.STATE_OFF:
                return "STATE_OFF";
            case BluetoothAdapter.STATE_TURNING_OFF:
                return "STATE_TURNING_OFF";
            case BluetoothAdapter.STATE_ON:
                return "STATE_ON";
            case BluetoothAdapter.STATE_TURNING_ON:
                return "STATE_TURNING_ON";
            }
            return "ERROR" + state;
        }
    };

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    cordova.getActivity().registerReceiver(broadcastReceiver, filter);
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void waitForPageLoaded(Bundle savedInstanceState) {
    final String savedHash = savedInstanceState != null
            ? savedInstanceState.getString(EXTRA_SAVED_ATTACHMENTHASH)
            : null;//from   www.java  2 s . c om
    if (savedHash != null)
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction() != null
                        && intent.getAction().equals(BoardFragment.BROADCAST_PAGE_LOADED)) {
                    unregisterReceiver(this);
                    broadcastReceiver = null;

                    Intent activityIntent = getIntent();
                    String pagehash = activityIntent.getStringExtra(EXTRA_PAGEHASH);
                    if (pagehash != null && remote.isPageLoaded(pagehash)) {
                        startActivity(activityIntent.putExtra(EXTRA_SAVED_ATTACHMENTHASH, savedHash));
                        finish();
                    }
                }
            }
        }, new IntentFilter(BoardFragment.BROADCAST_PAGE_LOADED));
}

From source file:com.mobiperf.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("Service onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());
    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();
    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.pauseRequested = true;
    this.stopRequested = false;
    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.taskQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult>>();

    // expect it to be the same size as the queue
    this.currentSchedule = new Hashtable<String, MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE);

    this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    restoreState();/*www  .  ja  va 2s . co  m*/

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.PREFERENCE_ACTION);
    filter.addAction(UpdateIntent.MSG_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);

    broadcastReceiver = new BroadcastReceiver() {
        // Handles various broadcast intents.

        // If traffic is paused by RRCTrafficControl (because a RRC test is
        // running), we do not perform the checkin, since sending interfering
        // traffic makes the RRC inference task abort and restart the current
        // test as the traffic may have altered the phone's RRC state.
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UpdateIntent.PREFERENCE_ACTION)) {
                updateFromPreference();
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)
                            && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("Checkin intent received");
                handleCheckin(false);
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)
                    && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("MeasurementIntent intent received");
                handleMeasurement();
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                Logger.d("MeasurementIntent update intent received");
                if (intent.getIntExtra(UpdateIntent.PROGRESS_PAYLOAD,
                        Config.INVALID_PROGRESS) == Config.MEASUREMENT_END_PROGRESS) {
                    if (intent.getStringExtra(UpdateIntent.ERROR_STRING_PAYLOAD) != null) {
                        failedMeasurementCnt++;
                    } else {
                        // Process result
                        completedMeasurementCnt++;
                    }
                    if (intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD) != null) {
                        Logger.d("Measurement result intent received");
                        saveResultToFile(intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD));

                    }
                    updateResultsConsole(intent);
                }
            } else if (intent.getAction().equals(UpdateIntent.MSG_ACTION)) {
                String msg = intent.getExtras().getString(UpdateIntent.STRING_PAYLOAD);
                Date now = Calendar.getInstance().getTime();
                insertStringToConsole(systemConsole, now + "\n\n" + msg);
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
    // TODO(mdw): Make this a user-selectable option
    addIconToStatusBar();
}

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

private void sendMMS(final byte[] bytesToSend) {
    revokeWifi(true);//from  w w  w  .  java2s. co m

    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    int result = beginMmsConnectivity();

    if (LOCAL_LOGV)
        Log.v(TAG, "result of connectivity: " + result + " ");

    if (result != 0) {
        // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        final BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context1, Intent intent) {
                String action = intent.getAction();

                if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    return;
                }

                @SuppressWarnings("deprecation")
                NetworkInfo mNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
                    return;
                }

                if (!mNetworkInfo.isConnected()) {
                    return;
                } else {
                    // ready to send the message now
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending through broadcast receiver");
                    alreadySending = true;
                    sendData(bytesToSend);

                    context.unregisterReceiver(this);
                }

            }

        };

        context.registerReceiver(receiver, filter);

        try {
            Looper.prepare();
        } catch (Exception e) {
            // Already on UI thread probably
        }

        // try sending after 3 seconds anyways if for some reason the receiver doesn't work
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!alreadySending) {
                    try {
                        if (LOCAL_LOGV)
                            Log.v(TAG, "sending through handler");
                        context.unregisterReceiver(receiver);
                    } catch (Exception e) {

                    }

                    sendData(bytesToSend);
                }
            }
        }, 7000);
    } else {
        // mms connection already active, so send the message
        if (LOCAL_LOGV)
            Log.v(TAG, "sending right away, already ready");
        sendData(bytesToSend);
    }
}

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

private void sendMMSWiFi(final byte[] bytesToSend) {
    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo.State state = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getState();

    if ((0 == state.compareTo(NetworkInfo.State.CONNECTED)
            || 0 == state.compareTo(NetworkInfo.State.CONNECTING))) {
        sendData(bytesToSend);//from   w w w  . j  av  a2s.  c om
    } else {
        int resultInt = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");

        if (resultInt == 0) {
            try {
                Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                sendData(bytesToSend);
            } catch (Exception e) {
                Log.e(TAG, "exception thrown", e);
                sendData(bytesToSend);
            }
        } else {
            // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            final BroadcastReceiver receiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context1, Intent intent) {
                    String action = intent.getAction();

                    if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                        return;
                    }

                    NetworkInfo mNetworkInfo = mConnMgr.getActiveNetworkInfo();
                    if ((mNetworkInfo == null)
                            || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE_MMS)) {
                        return;
                    }

                    if (!mNetworkInfo.isConnected()) {
                        return;
                    } else {
                        alreadySending = true;

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }

                        context.unregisterReceiver(this);
                    }

                }

            };

            context.registerReceiver(receiver, filter);

            try {
                Looper.prepare();
            } catch (Exception e) {
                // Already on UI thread probably
            }

            // try sending after 3 seconds anyways if for some reason the receiver doesn't work
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!alreadySending) {
                        try {
                            context.unregisterReceiver(receiver);
                        } catch (Exception e) {

                        }

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }
                    }
                }
            }, 7000);
        }
    }
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Handle incoming intents. Do not load a product if we already have one.
 *//* ww w  .  j  a v  a2s. c o m*/
@Override
protected void onResume() {
    super.onResume();

    String[] options = { InternalConstants.PRODUCT_OPTION_BASIC, InternalConstants.PRODUCT_OPTION_CATEGORIES,
            InternalConstants.PRODUCT_OPTION_CLASSIFICATION, InternalConstants.PRODUCT_OPTION_DESCRIPTION,
            InternalConstants.PRODUCT_OPTION_GALLERY, InternalConstants.PRODUCT_OPTION_PRICE,
            InternalConstants.PRODUCT_OPTION_PROMOTIONS, InternalConstants.PRODUCT_OPTION_REVIEW,
            InternalConstants.PRODUCT_OPTION_STOCK, InternalConstants.PRODUCT_OPTION_VARIANT };

    String productCode = null;

    Intent intent = getIntent();

    // Direct Call
    if (intent.hasExtra(DataConstants.PRODUCT_CODE)) //direct call from search list for example
    {
        productCode = intent.getStringExtra(DataConstants.PRODUCT_CODE);
    }
    // NFC Call
    else if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) //NFC 
    {
        Tag tag = getIntent().getExtras().getParcelable(NfcAdapter.EXTRA_TAG);

        Ndef ndef = Ndef.get(tag);
        NdefMessage message = ndef.getCachedNdefMessage();

        NdefRecord record = message.getRecords()[0];
        if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN
                && Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
            productCode = RegexUtil
                    .getProductCode(new String(record.getPayload(), 1, record.getPayload().length - 1));
        }
    }
    // Call from another application (QR Code) 
    else if (StringUtils.equals(intent.getAction(), Intent.ACTION_VIEW)) {
        productCode = RegexUtil.getProductCode(intent.getDataString());
    }

    if (StringUtils.isNotEmpty(productCode)) {
        this.enableAndroidBeam(productCode);
    }

    // Only load if we don't have a product already
    if (mProduct == null) {
        populateProduct(productCode, options);
    }

    invalidateOptionsMenu();
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * connect to the notification manager and create a notification builder.
 * it also setup the cancellation Intent for get notified when our notification got cancelled.
 *///from w  w  w. ja  va2 s  .  co m
private void setupNotification() {
    // get notification manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // get notification builder
    mBuilder = new NotificationCompat.Builder(this);
    // create a broadcast receiver to get actions
    // performed on the notification by the user
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            // user cancelled our notification
            if (action.equals(NOTIFICATION_CANCELLED)) {
                mRunning = false;
            }
        }
    };
    // register our receiver
    registerReceiver(mReceiver, new IntentFilter(NOTIFICATION_CANCELLED));
    // set common notification actions
    mBuilder.setDeleteIntent(
            PendingIntent.getBroadcast(this, CANCEL_CODE, new Intent(NOTIFICATION_CANCELLED), 0));
    mBuilder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
}

From source file:ca.mudar.snoozy.receiver.PowerConnectionReceiver.java

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

    final Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

    // Get user preferences
    final SharedPreferences sharedPrefs = context.getSharedPreferences(Const.APP_PREFS_NAME,
            Context.MODE_PRIVATE);
    final SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
    final boolean hasNotifications = sharedPrefs.getBoolean(Const.PrefsNames.HAS_NOTIFICATIONS, false);
    final boolean hasVibration = (sharedPrefs.getBoolean(Const.PrefsNames.HAS_VIBRATION, false)
            && vibrator.hasVibrator());
    final boolean hasSound = sharedPrefs.getBoolean(Const.PrefsNames.HAS_SOUND, false);
    final boolean onScreenLock = sharedPrefs.getBoolean(Const.PrefsNames.ON_SCREEN_LOCK, true);
    final boolean onPowerLoss = sharedPrefs.getBoolean(Const.PrefsNames.ON_POWER_LOSS, false);
    final int delayToLock = Integer.parseInt(
            sharedPrefs.getString(Const.PrefsNames.DELAY_TO_LOCK, Const.PrefsValues.DELAY_FAST)) * 1000;
    final int notifyCount = sharedPrefs.getInt(Const.PrefsNames.NOTIFY_COUNT, 1);
    final int notifyGroup = sharedPrefs.getInt(Const.PrefsNames.NOTIFY_GROUP, 1);

    final String action = intent.getAction();
    if (action == null)
        return;//from   w  w w.  j a  v a  2s  .co  m

    if (action.equals(Const.IntentActions.NOTIFY_DELETE)) {
        if (hasNotifications) {
            // Reset the notification counter (and group) on NOTIFY_DELETE
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_COUNT, 1);
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_GROUP, notifyGroup + 1);
            sharedPrefsEditor.apply();
        }
    } else if (action.equals(Intent.ACTION_POWER_CONNECTED)
            || action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        final boolean isConnectedPower = action.equals(Intent.ACTION_POWER_CONNECTED);

        // Lock the screen, following the user preferences
        if (delayToLock == 0) {
            LockScreenHelper.lockScreen(context, onScreenLock, onPowerLoss, isConnectedPower);
        } else {
            Intent intentService = new Intent(Intent.ACTION_SYNC, null, context, DelayedLockService.class);
            Bundle extras = new Bundle();
            extras.putBoolean(Const.IntentExtras.ON_SCREEN_LOCK, onScreenLock);
            extras.putBoolean(Const.IntentExtras.ON_POWER_LOSS, onPowerLoss);
            extras.putBoolean(Const.IntentExtras.IS_CONNECTED, isConnectedPower);
            extras.putInt(Const.IntentExtras.DELAY_TO_LOCK, delayToLock);
            intentService.putExtras(extras);
            context.startService(intentService);
        }

        // Save in database
        saveHistoryItem(context.getApplicationContext(), isConnectedPower, notifyGroup);

        if (hasNotifications) {
            // Send notification, with sound and vibration
            notify(context, isConnectedPower, hasVibration, hasSound, notifyCount);

            // Increment the notification counter
            sharedPrefsEditor.putInt(Const.PrefsNames.NOTIFY_COUNT, notifyCount + 1);
            sharedPrefsEditor.apply();
        } else {
            // Native Vibration or Sound, without Notifications
            nativeVibrate(context, hasVibration);

            nativeRingtone(context, hasSound);
        }
    }
}