Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

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

Prototype

public BroadcastReceiver() 

Source Link

Usage

From source file:com.hyphenate.chatuidemo.ui.MainActivity.java

/**
 * debug purpose only, you can ignore this
 *///from   w  w  w .  j ava2s.co m
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            DemoHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.yangtsaosoftware.pebblemessenger.services.PebbleCenter.java

@Override
public void onCreate() {
    super.onCreate();
    Handler pebbleCenterHandler = new PebbleCenterHandler();
    mPebbleCenterHandler = new Messenger(pebbleCenterHandler);
    Constants.log(TAG_NAME, "Create PebbleCenter Messenger.");
    loadPref();//from  w  w  w .j  a v  a2  s  . c  om
    _contex = this;
    //   busyBegin=new Time();
    //        waitQueue=new ArrayDeque<PebbleMessage>();
    sendQueue = new ArrayDeque<PebbleDictionary>();
    bindService(new Intent(this, MessageProcessingService.class), connToMessageProcessing,
            Context.BIND_AUTO_CREATE);
    Thread prepareThread = new PrepareThread();
    prepareThread.start();
    Thread sendMsgThread = new SendMsgThread();
    sendMsgThread.start();
    isPebbleEnable = PebbleKit.isWatchConnected(_contex);
    PebbleKit.registerReceivedDataHandler(_contex, new PebbleKit.PebbleDataReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveData(Context context, int transactionId, PebbleDictionary data) {
            PebbleKit.sendAckToPebble(_contex, transactionId);
            //          appStatue++;
            Constants.log(TAG_NAME, "Received data form pebble");
            switch (data.getUnsignedIntegerAsLong(ID_COMMAND).intValue()) {
            case REQUEST_TRANSID_CALL_TABLE: {
                Constants.log(TAG_NAME, "Request call table.");
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_CALL_TABLE;
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_MESSAGE_TABLE: {
                Constants.log(TAG_NAME, "Request message table.");
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_MESSAGE_TABLE;
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_CALL: {
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_CALL;
                Bundle b = new Bundle();
                b.putString(MessageDbHandler.COL_CALL_ID, data.getString(ID_EXTRA_DATA));
                Constants.log(TAG_NAME, "Request call id:" + data.getString(ID_EXTRA_DATA));

                msg.setData(b);
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
                break;
            case REQUEST_TRANSID_MESSAGE:
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_MESSAGE;
                Bundle b = new Bundle();
                b.putString(MessageDbHandler.COL_MESSAGE_ID, data.getString(ID_EXTRA_DATA));
                Constants.log(TAG_NAME, "Request message id:" + data.getString(ID_EXTRA_DATA));

                msg.setData(b);
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_TRANSID_PICKUP_PHONE:
                TelephonyManager telMag = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                Constants.log("Receivephone", "Receive phone:" + data.getString(ID_EXTRA_DATA2));
                if (telMag.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
                    switch (data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).intValue()) {
                    case REQUEST_EXTRA_SPEAKER_ON:
                        answerCall(true);
                        break;
                    case REQUEST_EXTRA_SPEAKER_OFF:
                        answerCall(false);
                        break;
                    }
                } else {
                    switch (data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).intValue()) {
                    case REQUEST_EXTRA_SPEAKER_ON:
                        dialNumber(data.getString(ID_EXTRA_DATA2), true);
                        break;
                    case REQUEST_EXTRA_SPEAKER_OFF:
                        dialNumber(data.getString(ID_EXTRA_DATA2), false);
                        break;
                    }

                }
                //                pebbleBusy = false;
                break;
            case REQUEST_TRANSID_HANGOFF_PHONE:
                endCall();
                //                pebbleBusy=false;

                break;
            case REQUEST_TRANSID_HANGOFF_SMS1:
                Constants.log(TAG_NAME, "Request hangoff and send sms1");

                endCall();
                doSendSMSTo(data.getString(ID_EXTRA_DATA), sms1);
                //               pebbleBusy=false;

                break;
            case REQUEST_TRANSID_HANGOFF_SMS2:
                Constants.log(TAG_NAME, "Request hangoff and send sms2");

                endCall();
                doSendSMSTo(data.getString(ID_EXTRA_DATA), sms2);
                //              pebbleBusy=false;

                break;
            case REQUEST_TRANSID_CLOSE_APP:
                Constants.log(TAG_NAME, "Request close app command.");
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
                //               need_delay=true;

                break;
            case REQUEST_TRANSID_NEXTPAGE:
                Constants.log(TAG_NAME, "Request send next page.");

                sendMsgThreadHandler.sendEmptyMessage(SEND_NEXT_PAGE);
                break;
            case REQUEST_TRANSID_READ_NOTIFY: {
                Constants.log(TAG_NAME, "Request  read msg");
                Message read_msg = Message.obtain();
                read_msg.what = MessageProcessingService.MSG_READ;
                Bundle bd = new Bundle();
                bd.putString(MessageDbHandler.COL_MESSAGE_ID,
                        data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).toString());
                read_msg.setData(bd);
                try {
                    rMessageProcessingHandler.send(read_msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_IM_FREE:
                Constants.log(TAG_NAME, "Request pebble app is free to receive data.");

                //               need_delay = data.getUnsignedInteger(ID_EXTRA_DATA).intValue() == REQUEST_EXTRA_DELAY_ON ;
                //               clean_SendQue();
                break;
            case REQUEST_TRANSID_VERSION: {
                send_test_get_return = true;
                String result = data.getString(ID_EXTRA_DATA);
                Constants.log("PmpVersion", result);
                StringTokenizer tokens = new StringTokenizer(result, ".");

                Intent inner_intent = new Intent(SetupFragment.class.getName());
                inner_intent.putExtra(Constants.BROADCAST_VERSION,
                        new byte[] { Byte.parseByte(tokens.nextToken()), Byte.parseByte(tokens.nextToken()),
                                Byte.parseByte(tokens.nextToken()) });
                LocalBroadcastManager.getInstance(context).sendBroadcast(inner_intent);
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
                break;
            }
            }
        }
    });

    PebbleKit.registerReceivedAckHandler(_contex, new PebbleKit.PebbleAckReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveAck(Context context, int transactionId) {
            Constants.log(TAG_NAME, "Get a receiveAck:" + String.valueOf(transactionId));
            switch (transactionId) {
            case TRANS_ID_COMMON:
                Constants.log(TAG_NAME, "Send continue...");
                //                  pebbleBusy=true;
                sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                break;
            case TRANS_ID_END:
                send_full_page = true;
                break;
            case TRANS_ID_EMPTY:
                //                 pebbleBusy=true;
                sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                break;
            case TRANS_ID_TEST: {
                break;
            }
            }
        }
    });

    PebbleKit.registerReceivedNackHandler(_contex, new PebbleKit.PebbleNackReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveNack(Context context, int transactionId) {
            Constants.log(TAG_NAME, "Get a receivedNack:" + String.valueOf(transactionId));
            if (PebbleKit.isWatchConnected(_contex)) {
                switch (transactionId) {
                case TRANS_ID_COMMON:
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                    break;
                case TRANS_ID_END:
                    send_full_page = true;
                    break;
                case TRANS_ID_EMPTY:
                    //                   appStatue=0;
                    sendMsgThreadHandler.sendEmptyMessage(SEND_OPEN_APP);
                    break;
                case TRANS_ID_TEST: {
                    Intent inner_intent = new Intent(SetupFragment.class.getName());
                    inner_intent.putExtra(Constants.BROADCAST_VERSION, new byte[] { 0, 0, 0 });
                    LocalBroadcastManager.getInstance(context).sendBroadcast(inner_intent);
                }
                }
            } else {
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
            }

        }
    });

    PebbleKit.registerPebbleConnectedReceiver(_contex, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isPebbleEnable = true;
        }
    });

    PebbleKit.registerPebbleDisconnectedReceiver(_contex, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isPebbleEnable = false;
            sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
        }
    });

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int command = intent.getIntExtra(Constants.BROADCAST_COMMAND, Constants.BROADCAST_PREFER_CHANGED);

            switch (command) {
            case Constants.BROADCAST_PREFER_CHANGED:
                loadPref();
                break;
            case Constants.BROADCAST_CALL_IDLE:
                if (callEnable) {
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CALL_END);
                }
                break;
            case Constants.BROADCAST_CALL_HOOK:
                if (callEnable) {
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CALL_HOOK);
                }
                break;
            case Constants.BROADCAST_PEBBLE_TEST:
                if (isPebbleEnable) {
                    prepareThreadHandler.sendEmptyMessage(PREPARE_TEST);
                }
                break;
            }
        }
    };
    IntentFilter intentFilter = new IntentFilter(PebbleCenter.class.getName());
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(br, intentFilter);
}

From source file:au.org.ala.fielddata.mobile.MobileFieldDataDashboard.java

private void listenForSurveyDownload() {
    broadcastReceiver = new BroadcastReceiver() {
        @Override/*  ww  w . j  a  va  2 s  .  co m*/
        public void onReceive(Context context, Intent intent) {
            boolean success = intent.getBooleanExtra(SurveyDownloadService.RESULT_EXTRA, false);
            if (success) {
                Toast.makeText(MobileFieldDataDashboard.this, "Surveys refreshed", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MobileFieldDataDashboard.this, "Refresh failed - please check your network",
                        Toast.LENGTH_LONG).show();
            }
            reloadTabs();
            setSupportProgressBarIndeterminateVisibility(false);
            stopListeningForSurveyDownload();
        }
    };
    IntentFilter downloadFilter = new IntentFilter(SurveyDownloadService.FINISHED_ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, downloadFilter);
}

From source file:cn.xcom.helper.chat.ui.MainActivity.java

/**
 * debug purpose only, you can ignore this
 *//*from  w  ww .j  av  a  2  s .c  om*/
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            DemoHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.tonyodev.fetch.FetchService.java

private void removeAll() {

    if (activeDownloads.size() > 0) {

        runningTask = true;//from   w w  w.  j av  a  2 s. c  o m

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (intent != null) {
                    long id = FetchRunnable.getIdFromIntent(intent);
                    removeAction(id);
                }

                if (activeDownloads.size() == 0) {
                    removeAllAction();
                    broadcastManager.unregisterReceiver(this);
                    registeredReceivers.remove(this);
                    runningTask = false;
                    startDownload();
                }
            }
        };

        registeredReceivers.add(broadcastReceiver);
        broadcastManager.registerReceiver(broadcastReceiver, FetchRunnable.getDoneFilter());
        interruptActiveDownloads();
    } else {
        removeAllAction();
        startDownload();
    }
}

From source file:com.avcall.app.ui.MainActivity.java

/**
 * debug purpose only, you can ignore this
 */// w w  w.  j  a va  2s  .  com
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            AvcallHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.easemob.ChuangKeYuan.ui.MainActivity.java

/**
 * ??/*from w w  w  .j a  va 2  s.com*/
 */
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            MyHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            // ??
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.asksven.betterbatterystats.StatsActivity.java

@Override
protected void onResume() {
    super.onResume();
    Log.i(TAG, "OnResume called");

    if (Analytics.getInstance(this).isEnabled()) {
        Tracking.startUsage(this);
    }/* ww w  .j a v a 2  s  .  c om*/

    // if debug we check for updates
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        if (pinfo.packageName.endsWith("_xdaedition")) {
            UpdateManager.register(this);
            CrashManager.register(this);
        }
    } catch (Exception e) {
        Log.e(TAG, "An error occured registering update/crash manager: " + e.getMessage());
    }

    // Analytics opt-in
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    boolean wasPresentedOptOutAnalytics = prefs.getBoolean("analytics_opt_out_offered", false);

    if (!wasPresentedOptOutAnalytics) {
        Log.i(TAG, "Application was launched for the first time with analytics");
        Snackbar.make(findViewById(android.R.id.content), R.string.message_first_start, Snackbar.LENGTH_LONG)
                .show();

        Snackbar bar = Snackbar.make(findViewById(android.R.id.content), R.string.pref_app_analytics_summary,
                Snackbar.LENGTH_LONG).setAction(R.string.label_button_no, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("analytics", false);
                        editor.commit();
                    }
                });

        bar.show();

        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("analytics_opt_out_offered", true);
        editor.commit();
    }

    Log.i(TAG, "OnResume called");

    Log.i(TAG, "onResume references state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
    // register the broadcast receiver
    IntentFilter intentFilter = new IntentFilter(ReferenceStore.REF_UPDATED);
    m_referenceSavedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //extract our message from intent
            String refName = intent.getStringExtra(Reference.EXTRA_REF_NAME);
            //log our message value

            if (LogSettings.DEBUG)
                Log.i(TAG, "Received broadcast, reference was updated:" + refName);

            // reload the spinners to make sure all refs are in the right sequence when current gets refreshed
            //                if (refName.equals(Reference.CURRENT_REF_FILENAME))
            //                {
            refreshSpinners();
            //                }
        }
    };

    //registering our receiver
    this.registerReceiver(m_referenceSavedReceiver, intentFilter);

    // the service is always started as it handles the widget updates too
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // show/hide spinners
    boolean showSpinners = sharedPrefs.getBoolean("show_from_to_ref", true);
    if (!showSpinners) {
        LinearLayout spinnerLayout = (LinearLayout) this.findViewById(R.id.LayoutSpinners);
        if (spinnerLayout != null) {
            spinnerLayout.setVisibility(View.GONE);
        }

    }

    if (!EventWatcherService.isServiceRunning(this)) {
        Intent i = new Intent(this, EventWatcherService.class);
        this.startService(i);
    }

    // make sure to create a valid "current" stat if none exists
    // or if prefs re set to auto refresh
    boolean bAutoRefresh = sharedPrefs.getBoolean("auto_refresh", true);

    if ((bAutoRefresh) || (!ReferenceStore.hasReferenceByName(Reference.CURRENT_REF_FILENAME, this))) {
        Intent serviceIntent = new Intent(this, WriteCurrentReferenceService.class);
        this.startService(serviceIntent);
        doRefresh(true);

    } else {
        refreshSpinners();
        doRefresh(false);

    }

    // check if active monitoring is on: if yes make sure the alarm is scheduled
    if (sharedPrefs.getBoolean("active_mon_enabled", false)) {
        if (!StatsProvider.isActiveMonAlarmScheduled(this)) {
            StatsProvider.scheduleActiveMonAlarm(this);
        }
    }
    //Log.i(TAG, "OnResume end");

    // we do some stuff here to handle settings about font size
    String fontSize = sharedPrefs.getString("medium_font_size", "16");
    int mediumFontSize = Integer.parseInt(fontSize);

    //we need to change "since" fontsize
    TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
    tvSince.setTextSize(TypedValue.COMPLEX_UNIT_SP, mediumFontSize);

}

From source file:com.easemob.chatuidemo.ui.MainActivity.java

/**
 * ??//from www. j a v  a  2 s.  c om
 */
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            DemoHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            // ??
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void setupFilter() {
    final IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.ACTION_REFRESH_STATUS);
    mReceiver = new BroadcastReceiver() {
        @Override/*from www . j a  va  2  s. c o  m*/
        public void onReceive(Context context, Intent intent) {
            // Got intent to clean up
            if (intent.getAction().equals(Constants.ACTION_REFRESH_STATUS)) {
                if (D)
                    Log.d(TAG, "onReceive intent " + intent.toString());
                List<Command> commands = mListAdapter.getCommands();
                // this list should be in the same order as in the ListBox
                int i = 0;
                for (Command cmd : commands) {
                    if (cmd.getDisplayStatus()) {
                        mSerialService.sendStatusCommand(cmd.getCommandStat(), i, false);
                    }
                    i++;
                }
            }
        }
    };
    registerReceiver(mReceiver, filter);
}