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.bayapps.android.robophish.MusicService.java

private void registerCarConnectionReceiver() {
    IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
    mCarConnectionReceiver = new BroadcastReceiver() {
        @Override//from  w w  w  .  j a va  2 s  .co  m
        public void onReceive(Context context, Intent intent) {
            String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
            mIsConnectedToCar = CarHelper.MEDIA_CONNECTED.equals(connectionEvent);
            LogHelper.i(TAG, "Connection event to Android Auto: ", connectionEvent, " isConnectedToCar=",
                    mIsConnectedToCar);
        }
    };
    registerReceiver(mCarConnectionReceiver, filter);
}

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

/**
 * ??// ww w  .  j av  a 2 s .  c om
 */
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            DemoHelper.getInstance().logout(true, 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.hhunj.hhudata.ForegroundService.java

private void sendSMS(String message) {

    if (message == "")
        return;/*w  w  w.  jav  a  2 s  .co  m*/

    //String stext  =  "  " +m_contactmap.size();

    //notification ,title
    showNotification("hhudata", message);

    if (m_alarmInWorktime) {//
        Date dt = new Date();
        if (IsDuringWorkHours(dt) == false) {
            return;
        } else {
            //alarm.

        }
    }

    if (message.length() > 140) {
        //....
        return;
    }

    // ---sends an SMS message to another device---
    SmsManager sms = SmsManager.getDefault();
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

    // create the sentIntent parameter
    Intent sentIntent = new Intent(SENT_SMS_ACTION);
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent, 0);

    // create the deilverIntent parameter
    Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);

    // register the Broadcast Receivers
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS sent success actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "SMS generic failure actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "SMS radio off failure actions", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "SMS null PDU failure actions", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }, new IntentFilter(SENT_SMS_ACTION));
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context _context, Intent _intent) {
            Toast.makeText(getBaseContext(), "SMS delivered actions", Toast.LENGTH_SHORT).show();
        }
    }, new IntentFilter(DELIVERED_SMS_ACTION));

    // if message's length more than 70 ,
    // then call divideMessage to dive message into several part ,and call
    // sendTextMessage()
    // else direct call sendTextMessage()

    Iterator it = m_contactmap.keySet().iterator();
    while (it.hasNext()) {
        ContactColumn.ContactInfo info = m_contactmap.get(it.next());
        if (info.mobile == null)
            continue;
        String mobile = info.mobile.trim();
        if (mobile.length() >= 4) {
            if (message.length() > 70) {

                ArrayList<String> msgs = sms.divideMessage(message);
                for (String msg : msgs) {
                    sms.sendTextMessage(mobile, null, msg, sentPI, deliverPI);
                }
            } else {
                sms.sendTextMessage(mobile, null, message, sentPI, deliverPI);
            }
        }
    }

}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
    // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");
    flagChatting = true;//from  ww w .j a va2s . c  om
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    offerId = 0;
    offerStatus = 0;
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    metrics = this.getResources().getDisplayMetrics();
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
            senderToken, recipientToken);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }
            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";

    Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
    if (chatRecipientUrl != null) {
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else if (chatRecipientUrl != "null") {
            url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
        }
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (final StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String durationStr = null;
            String fromStikyBee = chatTb.getSender();
            try {
                final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (chatTb.getFileName().contains("voice")) {
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);

                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    // Log.i(TAG, "Duration Srt " + durationStr);
                }
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                    //first false = right, second false = Offer
                    //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                    if (!chatTb.getFileName().contains("voice")) {
                        Log.i(TAG, " Voice is not ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        Log.i(TAG, " Voice is ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                } else {
                    /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                     Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                    // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    if (!chatTb.getFileName().contains("voice")) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            fileNameGCM = sharedPreferences.getString("fileName", "");
            messageGCM = sharedPreferences.getString("message", "");
            offerIdGCM = sharedPreferences.getInt("offerId", 0);
            offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
            priceGCM = sharedPreferences.getString("price", "");
            rateGCM = sharedPreferences.getString("rate", "");
            nameGCM = sharedPreferences.getString("name", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                    + priceGCM + " " + rateGCM);
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                    /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    oriFName = saveFileAndImage(fileNameGCM);
                    }*/
                    /*if (fileNameGCM.contains("voice")) {
                    String durationStr;
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                            
                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);
                            
                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                    adapter.add(stikyChat);
                    } else {*/
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                            fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                            oriFName);
                    adapter.add(stikyChat);
                    //  }
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());

                    adapter.notifyDataSetChanged();
                    lv.setSelection(adapter.getCount() - 1);
                    new regTask2().execute("Obj ");
                } else {
                    /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    saveFileAndImage(fileNameGCM);
                     }*/
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
            lv.setSelection(adapter.getCount() - 1);
        }
    };

    /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
      Toast.makeText(getBaseContext(),
                ((EditText) v).getId() + " has focus - " + hasFocus,
                Toast.LENGTH_LONG).show();
    }
    });*/
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
            /*getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
            );*/
            Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
            return false;
        }
    });
}

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

private void remove(final long id) {

    if (activeDownloads.containsKey(id)) {

        runningTask = true;/*w  w w  .  j  a  v  a  2s .c  o  m*/

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

                if (FetchRunnable.getIdFromIntent(intent) == id) {
                    removeAction(id);

                    broadcastManager.unregisterReceiver(this);
                    registeredReceivers.remove(this);
                    runningTask = false;
                    startDownload();
                }
            }
        };

        registeredReceivers.add(broadcastReceiver);
        broadcastManager.registerReceiver(broadcastReceiver, FetchRunnable.getDoneFilter());
        interruptActiveDownload(id);
    } else {
        removeAction(id);
        startDownload();
    }
}

From source file:com.lchtime.safetyexpress.ui.chat.hx.activity.ContactActivity.java

/**
 * debug purpose only, you can ignore this
 *///from  w  w  w . j  a  v  a2 s.c o 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(ContactActivity.this, LoginUI.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.polyvi.xface.extension.XAppExt.java

private void registerInstallerReceiver(final XCallbackContext callbackCtx) {
    if (null == mInstallerReceiver) {
        mInstallerReceiver = new BroadcastReceiver() {
            @Override//from w ww.ja  v a2 s  . c  o m
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")
                        && (uninstallPackageName.equals(intent.getDataString().substring(8)))) {
                    XExtensionResult result = new XExtensionResult(XExtensionResult.Status.OK);
                    callbackCtx.sendExtensionResult(result);
                }
                if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
                    XExtensionResult result = new XExtensionResult(XExtensionResult.Status.OK);
                    callbackCtx.sendExtensionResult(result);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        getContext().registerReceiver(mInstallerReceiver, filter);
    }
}

From source file:com.aegiswallet.actions.MainActivity.java

private void setupBlockchainBroadcastReceiver(final TextView blockchainStatus) {
    receiver = new BroadcastReceiver() {
        @Override//w  w w . j ava2s .co  m
        public void onReceive(Context context, Intent intent) {
            int download = intent.getIntExtra(PeerBlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD,
                    PeerBlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD_OK);
            Date bestChainDate = (Date) intent
                    .getSerializableExtra(PeerBlockchainService.ACTION_BLOCKCHAIN_STATE_BEST_CHAIN_DATE);

            long blockchainLag = System.currentTimeMillis() - bestChainDate.getTime();
            boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS;
            boolean downloadOk = download == PeerBlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD_OK;

            String downloading = downloadOk ? getString(R.string.synchronizing_network)
                    : getString(R.string.sync_stalled);

            Date currentDate = new Date();
            long daysOutOfDate = TimeUnit.MILLISECONDS.toDays(currentDate.getTime() - bestChainDate.getTime())
                    + 1;

            if (!blockchainUptodate) {
                blockchainStatus.setText(
                        downloading + " " + daysOutOfDate + " " + getString(R.string.sync_days_behind));
                blockchainStatus.setTextColor(getResources().getColor(R.color.custom_red));
            } else {
                blockchainStatus.setText(getString(R.string.sync_completed));
                blockchainStatus.setTextColor(getResources().getColor(R.color.custom_green));
            }

            updateMainViews();
        }
    };
}

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

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

        @Override
        public void onReceive(Context context, Intent intent) {
            EMHelper.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.supremainc.biostar2.monitor.MonitorFragment.java

protected void registerBroadcast() {
    if (mReceiver == null) {
        mReceiver = new BroadcastReceiver() {
            @Override/*from  w ww .  ja v  a 2  s.  c o m*/
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();
                if (mIsDestroy) {
                    return;
                }
                if (action.equals(Setting.BROADCAST_PREFRENCE_REFRESH) && mMonitorAdapter != null) {
                    mMonitorAdapter.notifyDataSetChanged();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Setting.BROADCAST_PREFRENCE_REFRESH);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, intentFilter);
    }
}