Example usage for android.net ConnectivityManager CONNECTIVITY_ACTION

List of usage examples for android.net ConnectivityManager CONNECTIVITY_ACTION

Introduction

In this page you can find the example usage for android.net ConnectivityManager CONNECTIVITY_ACTION.

Prototype

String CONNECTIVITY_ACTION

To view the source code for android.net ConnectivityManager CONNECTIVITY_ACTION.

Click Source Link

Document

A change in network connectivity has occurred.

Usage

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

/**
 * onCreate/*from  w ww  .  j a  v a 2 s . c om*/
 * @param savedInstanceState
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
        // T??home???appcrash
        // fragment??
        finish();
        // startActivity(new Intent(this, LoginActivity.class));
        startActivity(new Intent(this, LoginDialogActivity.class));
        return;
    }
    setContentView(R.layout.activity_main);
    IntentFilter mFilter = new IntentFilter();
    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(myNetReceiver, mFilter);
    initView();
    //        MobclickAgent.setDebugMode(true);
    //        MobclickAgent.updateOnlineConfig(this);
    //        EMChatManager.getInstance().getChatOptions().setShowNotificationInBackgroud(false);
    if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow)
        showConflictDialog();

    inviteMessgeDao = new InviteMessgeDao(this);
    //  userDao = new UserDao(this);

    // fragment???
    // chatHistoryFragment = new ChatHistoryFragment();
    // ?fragment
    chatHistoryFragment = new ChatAllHistoryFragment();
    //        contactListFragment = new ContactlistFragment();
    settingFragment = new SettingsFragment();
    indexFragment = new IndexFragment();
    mChatAllHistoryFProvider = new ChatAllHistoryFProvider(getApplicationContext());
    //        surroundingsFragment = new SurroundingsFragment();
    //        peripheryFragment = new PeripheryFragment();
    newSurroundingFrg = new NewSurroundingFrg();

    meFragment = new MeFragment();

    //        fragments = new Fragment[]{indexFragment, chatHistoryFragment,
    //                surroundingsFragment, meFragment};

    fragments = new Fragment[] { indexFragment, chatHistoryFragment, newSurroundingFrg, meFragment };

    tv_notifycount = (TextView) findViewById(R.id.tv_newnotify_count);

    // ?
    viewPager = (ViewPager) findViewById(R.id.vp_index);
    viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
    viewPager.setOffscreenPageLimit(3);
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            mTabs[currentTabIndex].setSelected(false);
            // ?tab?
            mTabs[arg0].setSelected(true);
            currentTabIndex = arg0;

            switch (arg0) {
            case 0:
                indexFragment.getLifeCircleCount(handler);
                break;
            case 2:
                Log.i("debbug", "0");
                PreferencesUtil.saveCrazySalesCount(MainActivity.this, 0);
                unreadAddressLabel.setVisibility(View.INVISIBLE);

                //                        indexFragment.eventService("" + 18, "");

                newSurroundingFrg.updateUI();
                //                        peripheryFragment.updateUI();

            case 3:
                Log.i("meFragement tags ", "");
                PreferencesUtil.saveIsUnReadTagsChange(MainActivity.this, false);
                break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    /* IntentFilter offlineMessageIntentFilter = new
        IntentFilter(EMChatManager.getInstance()
        .getOfflineMessageBroadcastAction());
     offlineMessageIntentFilter.setPriority(6);
     registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);
     // ?BroadcastReceiver
     msgReceiver = new NewMessageBroadcastReceiver();
     IntentFilter intentFilter = new IntentFilter(EMChatManager
        .getInstance().getNewMessageBroadcastAction());
            
     intentFilter.setPriority(3);
     registerReceiver(msgReceiver, intentFilter);
            
     // ack?BroadcastReceiver
     IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager
        .getInstance().getAckMessageBroadcastAction());
     ackMessageIntentFilter.setPriority(3);
     registerReceiver(ackMessageReceiver, ackMessageIntentFilter);
            
     // ??BroadcastReceiver
     IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager
        .getInstance().getCmdMessageBroadcastAction());
     cmdMessageIntentFilter.setPriority(3);
     registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);*/

    // ?BroadcastReceiver

    //EMChatManager.getInstance().getChatOptions().setNotifyText(new OnMessageNotifyListener() {
    //    @Override
    //    public String onNewMessageNotify(EMMessage message) {
    //        operatNewMessage(message);
    //        return message.getBody().toString();
    //    }
    //
    //    @Override
    //    public String onLatestMessageNotify(EMMessage message, int i, int i2) {
    //        return null;
    //    }
    //
    //    @Override
    //    public String onSetNotificationTitle(EMMessage message) {
    //        return message.getStringAttribute(Config.EXPKey_nickname,"");
    //    }
    //
    //    @Override
    //    public int onSetSmallIcon(EMMessage message) {
    //        return R.drawable.me_arrow;
    //    }
    //});
    // setContactListener???
    EMContactManager.getInstance().setContactListener(new MyContactListener());
    // ??listener
    EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
    // ?listener
    EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());

    // sdkUI ??receiverlistener, ??broadcast
    EMChat.getInstance().setAppInited();

    AppLoginInfoBean.Info info = (AppLoginInfoBean.Info) getIntent()
            .getSerializableExtra(Config.IsLoginOtherApp);
    if (null != info) {
        showLogoutDialog("" + StrUtils.getTime4Millions(info.getLoginTime() * 1000L) + "\nid:"
                + info.getEquipment());
    }

    checkPushUpdate();

    //        UpdateUtils.initUpdate(getmContext());

    //        getRecords(getContentResolver());

    //// 2015/11/11 
    //        if(TimeUtils.isNeedShowRPTopList(this)){
    //            startActivity(new Intent(this, LastWeekRPValueTopListActivity.class));
    //        }

    ////
    //        handler.postDelayed(checkAppUpdate, new Random().nextInt(5) * 1000);
    initUpdate();

    //// ? , ,  , 
    //        PreferencesUtil.setFirstOpen(getmContext(), true);
    if (PreferencesUtil.isFirstOpen(getmContext())) {
        fetchCommunityCategoryData();
    }
    //// ???  2016/1/6
    if (PreferencesUtil.getLogin(this)) {
        long communityId = PreferencesUtil.getLoginInfo(this).getCommunityId();
        String emobId = PreferencesUtil.getLoginInfo(this).getEmobId();
        getGroupMsgsCall((int) communityId, emobId);
    }
    /// X5WebCore
    //        if(!isX5WebViewEnabled){
    //            preinitX5WebCore();
    //        }

}

From source file:com.ubuntuone.android.files.service.UpDownService.java

private void registerConnectivityReceiver(BroadcastReceiver receiver) {
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    getApplicationContext().registerReceiver(receiver, filter);
}

From source file:org.torproject.android.service.TorService.java

@Override
public void onCreate() {
    super.onCreate();

    try {//from ww w .  jav a2 s  .c o  m
        mNumberFormat = NumberFormat.getInstance(Locale.getDefault()); //localized numbers!

        if (mNotificationManager == null) {

            IntentFilter mNetworkStateFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(mNetworkStateReceiver, mNetworkStateFilter);

            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        }

        new Thread(new Runnable() {
            public void run() {
                try {

                    torUpgradeAndConfig();

                    findExistingTorDaemon();
                } catch (Exception e) {
                    Log.e(TAG, "error onBind", e);
                    logNotice("error finding exiting process: " + e.toString());
                }

            }
        }).start();

    } catch (Exception e) {
        //what error here
        Log.e(TAG, "Error installing Orbot binaries", e);
        logNotice("There was an error installing Orbot binaries");
    }

    Log.i("TorService", "onCreate end");
}

From source file:cz.muni.fi.japanesedictionary.parser.ParserService.java

/**
 * Downloads dictionaries./*from w  w w.j  a v  a 2s . c  om*/
 */

protected void onHandleIntent() {

    Log.i(LOG_TAG, "Creating parser service");

    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this).setAutoCancel(false).setOngoing(true)
            .setContentTitle(getString(R.string.dictionary_download_title))
            .setContentText(getString(R.string.dictionary_download_in_progress) + " (1/5)")
            .setSmallIcon(R.drawable.ic_notification).setProgress(100, 0, false).setContentInfo("0%")
            .setContentIntent(resultPendingIntent);

    startForeground(0, mNotification);
    mNotifyManager.notify(0, mBuilder.build());
    File storage;
    if (MainActivity.canWriteExternalStorage()) {
        // external storage available
        storage = getExternalCacheDir();
    } else {
        storage = getCacheDir();
    }
    if (storage == null) {
        throw new IllegalStateException("External storage isn't accessible");
    }
    // free sapce controll
    StatFs stat = new StatFs(storage.getPath());
    long bytesAvailable;
    if (Build.VERSION.SDK_INT < 18) {
        bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
    } else {
        bytesAvailable = stat.getAvailableBytes();
    }
    long megAvailable = bytesAvailable / 1048576;
    Log.d(LOG_TAG, "Megs free :" + megAvailable);
    if (megAvailable < 140) {
        mInternetReceiver = null;
        mNotEnoughSpace = true;
        stopSelf(mStartId);
        return;
    }

    this.registerReceiver(mInternetReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean english = sharedPrefs.getBoolean("language_english", false);
    boolean french = sharedPrefs.getBoolean("language_french", false);
    boolean dutch = sharedPrefs.getBoolean("language_dutch", false);
    boolean german = sharedPrefs.getBoolean("language_german", false);
    boolean russian = sharedPrefs.getBoolean("language_russian", false);
    if (!english && !french && !dutch && !german && !russian) {
        Log.i(LOG_TAG, "Setting english as only translation language");
        SharedPreferences.Editor editor_lang = sharedPrefs.edit();
        editor_lang.putBoolean("language_english", true);
        editor_lang.commit();
    }

    String dictionaryPath;
    String kanjiDictPath;

    URL url;
    try {
        url = new URL(ParserService.DICTIONARY_PATH);
    } catch (MalformedURLException ex) {
        Log.e(LOG_TAG, "Error: creating url for downloading dictionary");
        return;
    }

    try {

        dictionaryPath = storage.getPath() + File.separator + "dictionary.zip";
        File outputFile = new File(dictionaryPath);
        if (outputFile.exists()) {
            outputFile.delete();
        }

        mDownloadJMDictFrom = url;
        mDownloadJMDictTo = outputFile;
        mDownloadingJMDict = true;
        mDownloadInProgress = true;

        // downloading kanjidict
        url = null;
        try {
            url = new URL(ParserService.KANJIDICT_PATH);
        } catch (MalformedURLException ex) {
            Log.e(LOG_TAG, "Error: creating url for downloading kanjidict2");
        }
        if (url != null) {
            kanjiDictPath = storage.getPath() + File.separator + "kanjidict.zip";
            File fileKanjidict = new File(kanjiDictPath);
            if (fileKanjidict.exists()) {
                fileKanjidict.delete();
            }
            mDownloadingKanjidic = false;
            mDownloadKanjidicFrom = url;
            mDownloadKanjidicTo = fileKanjidict;
        }

        mDownloadTatoebaIndicesFrom = new URL(ParserService.TATOEBA_INDICES_PATH);
        mDownloadTatoebaIndicesTo = new File(storage, "tatoeba-japanese.zip");
        if (mDownloadTatoebaIndicesTo.exists()) {
            mDownloadTatoebaIndicesTo.delete();
        }

        mDownloadTatoebaSentencesFrom = new URL(ParserService.TATOEBA_SENTENCES_PATH);
        mDownloadTatoebaSentencesTo = new File(storage, "tatoeba-translation.zip");
        if (mDownloadTatoebaSentencesTo.exists()) {
            mDownloadTatoebaSentencesTo.delete();
        }

        mDownloadKanjiVGFrom = new URL(ParserService.KANJIVG_PATH);
        mDownloadKanjiVGTo = new File(storage, "kanjivg.zip");
        if (mDownloadKanjiVGTo.exists()) {
            mDownloadKanjiVGTo.delete();
        }

        downloadDictionaries();

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "MalformedURLException wrong format of URL: " + e.toString());
        stopSelf(mStartId);
    } catch (IOException e) {
        Log.e(LOG_TAG, "IOException downloading interrupted: " + e.toString());
        stopSelf(mStartId);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(LOG_TAG, "Exception: " + e.toString());
        stopSelf(mStartId);
    }

}

From source file:org.jorge.cmp.ui.activity.MainActivity.java

private void registerLocalBroadcastReceiver() {
    if (mChatBroadcastReceiver != null) {
        return;/*w w  w .j a va 2  s  .  c o m*/
    }
    mChatBroadcastReceiver = new ChatOverviewBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(mContext.getString(R.string.event_login_failed));
    intentFilter.addAction(mContext.getString(R.string.event_chat_overview));
    intentFilter.addAction(mContext.getString(R.string.event_login_successful));
    intentFilter.addAction(mContext.getString(R.string.event_message_received));
    LocalBroadcastManager.getInstance(mContext).registerReceiver(mChatBroadcastReceiver, intentFilter);
}

From source file:org.qeo.android.service.QeoService.java

private void enableNetworkSettings() {
    LOG.fine("Enable network change monitoring");
    mOnNetworkConnectivityChanged = new BroadcastReceiver() {
        @SuppressLint("Wakelock")
        @Override/*from w  w  w . j a  v a  2 s .c  o  m*/
        public void onReceive(Context context, Intent intent) {

            /*
             * Check if there is still a connected active network interface. If not, take a wakelock to make sure
             * DDS has the time to let all of it's timers time out properly. This is especially needed when the
             * network goes down due to the device going in sleep mode.
             */
            ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInf = connMgr.getActiveNetworkInfo();
            if (((activeNetworkInf != null) && (!activeNetworkInf.isConnected()))
                    || (activeNetworkInf == null)) {
                PowerManager powerMgr = (PowerManager) getSystemService(POWER_SERVICE);
                PowerManager.WakeLock wakeLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

                LOG.info("Take wakelock for 40 seconds");
                wakeLock.acquire(40 * 1000);
            }

            configureNetworkSettings(activeNetworkInf);
        }

    };
    registerReceiver(mOnNetworkConnectivityChanged, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
    configureNetworkSettings(activeNetworkInfo);
}

From source file:org.ulteo.ovd.AndRdpActivity.java

@TargetApi(14)
@Override/*w  w  w.j  a  v a 2  s  .c  o m*/
protected void onResume() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(statusRun, filter);
    if (isConnected())
        rdp.draw();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB
            && Settings.getSystemUiLowProfile(this)) {
        hideSystemUi();
    }
    super.onResume();
}

From source file:com.amazonaws.mobileconnectors.cognito.DefaultDataset.java

@Override
public void synchronizeOnConnectivity(SyncCallback callback) {
    if (isNetworkAvailable(context)) {
        synchronize(callback);/*from w w w.j  a va 2s  .c  o m*/
    } else {
        discardPendingSyncRequest();
        LOGGER.debug(
                "Connectivity is unavailable. " + "Scheduling synchronize for when connectivity is resumed.");
        pendingSyncRequest = new SyncOnConnectivity(this, callback);
        // listen to only connectivity change
        context.registerReceiver(pendingSyncRequest, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}

From source file:com.halseyburgund.rwframework.core.RWService.java

@Override
public void onCreate() {
    super.onCreate();

    // create default configuration and tags
    configuration = new RWConfiguration(this);
    tags = new RWTags();

    // get default server url from resources and reset other critical vars
    mServerUrl = getString(R.string.rw_spec_server_url);
    mStreamUrl = null;//from   w ww . j  a  v a 2  s  . c  o  m

    // create a factory for actions
    mActionFactory = new RWActionFactory(this);

    // create a queue for actions
    RWActionQueue.instance().init(this);

    // listen to connectivity state broadcasts
    registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    // listen to own server calls success and failure broadcasts
    IntentFilter filter = createOperationsIntentFilter();
    filter.addAction(RW.CONFIGURATION_LOADED);
    filter.addAction(RW.NO_CONFIGURATION);
    registerReceiver(rwReceiver, filter);

    // setup for GPS callback
    RWLocationTracker.instance().init(this);
    RWLocationTracker.instance().addObserver(this);

    // setup a tracker for assets streamed by the server
    mAssetTracker = new RWStreamAssetsTracker(this);
}

From source file:uk.org.ngo.squeezer.NowPlayingFragment.java

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume...");

    // Start it and have it run forever (until it shuts itself down).
    // This is required so swapping out the activity (and unbinding the
    // service connection in onDestroy) doesn't cause the service to be
    // killed due to zero refcount.  This is our signal that we want
    // it running in the background.
    mActivity.startService(new Intent(mActivity, SqueezeService.class));

    if (mService != null) {
        maybeRegisterCallbacks(mService);
    }/*  www . j  a  v a 2 s.  co  m*/

    if (new Preferences(mActivity).isAutoConnect()) {
        mActivity.registerReceiver(broadcastReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}