Example usage for android.content IntentFilter addAction

List of usage examples for android.content IntentFilter addAction

Introduction

In this page you can find the example usage for android.content IntentFilter addAction.

Prototype

public final void addAction(String action) 

Source Link

Document

Add a new Intent action to match against.

Usage

From source file:com.intel.xdk.device.Device.java

private void registerScreenStatusReceiver() {

    if (screenStatusReceiver == null) {
        //Listener to the screen unlock event.

        screenStatusReceiver = new BroadcastReceiver() {

            @Override//from  www .  j ava 2 s  . co m
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    Log.d("screen_on", "Screen is on.");
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    Log.d("screen_lock", "Screen is off");
                    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.pause');e.success=true;document.dispatchEvent(e);";
                    injectJS(js);
                } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                    Log.d("user_present", "User is present.");
                    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.continue');e.success=true;document.dispatchEvent(e);";
                    injectJS(js);
                }

            }

        };
    }
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    activity.registerReceiver(screenStatusReceiver, filter);
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

private void registerNetworkReceiver() {
    if (networkReceiver == null && registerNetworkReiceiver) {
        networkReceiver = new NetworkStateBroadcastReceiver();
        IntentFilter intentFilter;
        intentFilter = new IntentFilter();
        // intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        Log.d(DEBUG_TAG, "registering receiver");
        context.registerReceiver(networkReceiver, intentFilter);
    }//from   www .j  a  v  a2  s.  c o m
}

From source file:com.cpic.taylor.logistics.activity.HomeActivity.java

public void registerMessageReceiver() {
    mMessageReceiver = new MessageReceiver();
    IntentFilter filter = new IntentFilter();
    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    filter.addAction(MESSAGE_RECEIVED_ACTION);
    registerReceiver(mMessageReceiver, filter);
}

From source file:com.cpic.taylor.logistics.activity.HomeActivity.java

public void registerConnectKickedReceive() {
    connectKickedReceiveBroadCast = new ConnectKickedReceiveBroadCast();
    IntentFilter filter = new IntentFilter();
    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    filter.addAction(KICKED_OFFLINE_BY_OTHER_CLIENT);
    registerReceiver(connectKickedReceiveBroadCast, filter);
}

From source file:com.android.music.MediaPlaybackActivity.java

@Override
public void onStart() {
    super.onStart();
    paused = false;/*from  w w  w .j  a va  2  s.c  o m*/

    mToken = MusicUtils.bindToService(this, osc);
    if (mToken == null) {
        // something went wrong
        mHandler.sendEmptyMessage(QUIT);
    }

    IntentFilter f = new IntentFilter();
    f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
    f.addAction(MediaPlaybackService.META_CHANGED);
    registerReceiver(mStatusListener, new IntentFilter(f));
    updateTrackInfo();
    long next = refreshNow();
    queueNextRefresh(next);
}

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//from   w w w .  j a va2s  .  c om
        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.moez.QKSMS.mmssms.Transaction.java

private void sendMMS(final byte[] bytesToSend) {
    revokeWifi(true);/*from   ww  w .  ja v a 2s  .c  om*/

    // 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.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();//from  w  w w .  j  a v  a2  s. c om

    // 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 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 ww .  j a va 2  s.  com
    } 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.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  av a  2 s.  c o m

    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);
        }
    }
}