Example usage for android.content Context WIFI_SERVICE

List of usage examples for android.content Context WIFI_SERVICE

Introduction

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

Prototype

String WIFI_SERVICE

To view the source code for android.content Context WIFI_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.net.wifi.WifiManager for handling management of Wi-Fi access.

Usage

From source file:com.appnexus.opensdkapp.MainActivity.java

/**
 * Upload log file to server every 24 hours
 *//* www . j  ava  2 s.  c om*/

private void checkToUploadLogFile() {
    long lastLogUploadTime = Prefs.getLastLogUpload(getBaseContext());
    long currentTime = System.currentTimeMillis();
    long oneDayInMillis = 86400000;
    if (currentTime - lastLogUploadTime > oneDayInMillis) {
        Clog.d(Constants.BASE_LOG_TAG, "Last log upload was more than a day ago. Check wifi");

        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            Clog.d(Constants.BASE_LOG_TAG, "Wifi is available. Upload log file.");

            //TODO: implement file upload

            boolean fileUploadSuccessful = false;

            if (fileUploadSuccessful) {
                Prefs prefs = new Prefs(getBaseContext());
                prefs.writeLong(Prefs.KEY_LAST_LOG_UPLOAD, System.currentTimeMillis());
                prefs.applyChanges();

                clearLogFile();
            }
        }
    }
}

From source file:com.aimfire.main.MainActivity.java

/**
 * Override Activity lifecycle method.//  w w w.j av  a  2  s . co  m
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        /*
         * if this is initial launch, start the service
         */
        startService(new Intent(this, AimfireService.class));
    }

    PreferenceManager.setDefaultValues(this, getString(R.string.settings_file), MODE_PRIVATE,
            R.xml.pref_settings, true);

    /*
     * check persistence storage, if this is the first time we run, save certain
     * flags (like features available). check showIntro flag and show intro if 
     * necessary
     */
    checkPreferences();

    /*
     * set up UI
     */
    setContentView(R.layout.activity_main);

    /*
     * show overflow button even if we have a physical menu button
     */
    forceOverflowButton();

    /*
     * make a backup if we find old, non-compatible cvr files
     */
    if (mShowIntro) {
        checkOldCvr();
    }

    /*
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    /*
     * create directories if not exist
     */
    if (!FileUtils.initStorage()) {
        Toast.makeText(this, R.string.error_accessing_storage, Toast.LENGTH_LONG).show();
        finish();
    }

    mThumbsPagerAdapter = new ThumbsPagerAdapter(getSupportFragmentManager());

    mThumbsPager = (ViewPager) findViewById(R.id.thumbs_pager);
    mThumbsPager.setAdapter(mThumbsPagerAdapter);

    mThumbsPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When swiping between pages, select the
            // corresponding tab.
            mTabPosition = position;
            getSupportActionBar().setSelectedNavigationItem(position);
        }
    });

    ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mMyMediaTab = bar.newTab();
    mMyMediaTab.setText(getResources().getString(R.string.tab_my_media_name));
    mMyMediaTab.setTabListener(this);

    mSharedMediaTab = bar.newTab();
    mSharedMediaTab.setText(getResources().getString(R.string.tab_shared_with_me_name));
    mSharedMediaTab.setTabListener(this);

    bar.addTab(mMyMediaTab, TAB_INDEX_MY_MEDIA);
    bar.addTab(mSharedMediaTab, TAB_INDEX_SHARED_MEDIA);

    /*
     * first launch of this activity, "Shared with Me" tab is the default.
     */
    if (savedInstanceState != null) {
        /*
         * restore tab position after screen rotation
         */
        mTabPosition = savedInstanceState.getInt(KEY_TAB_POSITION);
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onCreate: restored tab position=" + mTabPosition);
    } else {
        //mTabPosition = TAB_INDEX_MY_MEDIA;
        mTabPosition = TAB_INDEX_SHARED_MEDIA;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "onCreate: set initial tab position=" + mTabPosition);
    }

    mCameraFab = (FloatingActionButton) findViewById(R.id.cameraFAB);
    mCameraFab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

            if (!manager.isWifiEnabled()) {
                /*
                 * if wifi not enabled, no point to continue
                 */
                Toast.makeText(getApplicationContext(), R.string.error_wifi_off, Toast.LENGTH_LONG).show();
                return;
            }

            if (AudioConfigure.getAudioRouting() != AudioConfigure.AUDIO_ROUTING_BUILTIN) {
                Toast.makeText(getApplicationContext(), R.string.error_headset, Toast.LENGTH_LONG).show();
                return;
            }

            mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_ACTION_CAMERA, null);

            /*
             * initiate discovery request
             */
            mAimfireService.initDemo(true, ActivityCode.CAMCORDER.getValue(), null);
            Intent intent = new Intent(getApplicationContext(), CamcorderActivity.class);
            startActivityForResult(intent, ActivityCode.CAMCORDER.getValue());
        }
    });

    /*
     * initializes Aimfire service. if it is already started, bind to it
     */
    mAimfireServiceConn = new AimfireServiceConn(this);

    /*
     * binding doesn't happen until later. wait for it to happen in another 
     * thread and do the necessary initialization on it.
     */
    (new Thread(mAimfireServiceInitTask)).start();

    /*
     * display app build time in debug window
     */
    displayVersion();

    /*
     * show introduction with a delay (to allow onCreate init to finish)
     */
    if (mShowIntro) {
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.TUTORIAL_BEGIN, null);

        Handler mHandler = new Handler();
        mHandler.postDelayed(mIntroTask, 1000/*ms*/);

        /*
         * check if gyroscope is supported (important for Cardboard mode).
         * only show warning once after fresh install
         */
        checkGyroscope();
    } else if (mShowSurvey) {
        mFirebaseAnalytics.logEvent(MainConsts.FIREBASE_CUSTOM_EVENT_SHOW_SURVEY, null);

        Handler mHandler = new Handler();
        mHandler.postDelayed(mSurveyTask, 1000/*ms*/);
    }

    if ((savedInstanceState == null) && isDeviceOnline()) {
        /*
         * check if new version is available
         */
        startService(new Intent(this, VersionChecker.class));

        /*
         * download samples in the background (if necessary)
         */
        startService(new Intent(this, SamplesDownloader.class));

        /*
         * notify user if upgrade is available
         */
        if (mUpgradeAvailable) {
            notifyUpgrade();
        }
    }

    //(new Thread(mLatencyTestTask)).start();
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {

    if (intent == null) {
        return START_STICKY;
    }/*from   w w w .  j a  va  2 s.c  o m*/

    String action = intent.getAction();

    if (Intent.ACTION_BATTERY_CHANGED.equals(action) || Intent.ACTION_BATTERY_LOW.equals(action)
            || Intent.ACTION_BATTERY_OKAY.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
            Bundle battery = new Bundle();
            HostBatteryProfile.setLevel(battery, mHostBatteryManager.getBatteryLevel());
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (Intent.ACTION_POWER_CONNECTED.equals(action)
            || Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);
            Bundle charging = new Bundle();

            if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
                HostBatteryProfile.setCharging(charging, true);
            } else {
                HostBatteryProfile.setCharging(charging, false);
            }

            HostBatteryProfile.setBattery(mIntent, charging);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (action.equals("android.intent.action.NEW_OUTGOING_CALL")) {
        // Phone

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostPhoneProfile.PROFILE_NAME, null,
                HostPhoneProfile.ATTRIBUTE_ON_CONNECT);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostPhoneProfile.setAttribute(mIntent, HostPhoneProfile.ATTRIBUTE_ON_CONNECT);
            Bundle phoneStatus = new Bundle();
            HostPhoneProfile.setPhoneNumber(phoneStatus, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
            HostPhoneProfile.setState(phoneStatus, CallState.START);
            HostPhoneProfile.setPhoneStatus(mIntent, phoneStatus);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)
            || WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        // Wifi

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);
            Bundle wifiConnecting = new Bundle();
            WifiManager wifiMgr = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
            HostConnectProfile.setEnable(wifiConnecting, wifiMgr.isWifiEnabled());
            HostConnectProfile.setConnectStatus(mIntent, wifiConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);
            Bundle bluetoothConnecting = new Bundle();
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            HostConnectProfile.setEnable(bluetoothConnecting, mBluetoothAdapter.isEnabled());
            HostConnectProfile.setConnectStatus(mIntent, bluetoothConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    }
    return super.onStartCommand(intent, flags, startId);
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

/**
 * Uses TelephonyManager and WifiManager to check for network connectivity.
 * Also incorporates CONNECTING state for retry scenarios.
 * @param context/*from w w w . j a v a 2  s .  com*/
 * @return ConnectionStatus
 */
public ConnectionStatus isConnectedOLD(Context context) {
    boolean data = false, wifi = false;
    boolean data_connecting = false, wifi_connecting = false;
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ds = tm.getDataState();
    int ws = wm.getWifiState();
    switch (ds) {
    case TelephonyManager.DATA_CONNECTED:
        data = true;
        break;
    case TelephonyManager.DATA_CONNECTING:
        data_connecting = true;
    default:
        data = false;
        data_connecting = false;
    }

    switch (ws) {
    case WifiManager.WIFI_STATE_ENABLING:
        wifi_connecting = true;
    case WifiManager.WIFI_STATE_DISABLING:
    case WifiManager.WIFI_STATE_DISABLED:
    case WifiManager.WIFI_STATE_UNKNOWN:
        wifi = false;
        break;
    case WifiManager.WIFI_STATE_ENABLED:
        WifiInfo wi = wm.getConnectionInfo();
        if (wi != null)
            wifi = true;
        break;
    }

    if (wifi && data)
        return ConnectionStatus.BOTH_CONNECTED;
    else if (wifi && data_connecting)
        return ConnectionStatus.WIFI_CONNECTED;
    else if (data && wifi_connecting)
        return ConnectionStatus.DATA_CONNECTED;
    else if (wifi_connecting || data_connecting)
        return ConnectionStatus.CONNECTING;
    return ConnectionStatus.NO_CONNECTION;
}

From source file:com.otaupdater.utils.Utils.java

public static String getDeviceID(Context ctx) {
    if (deviceID != null)
        return deviceID;

    deviceID = ((TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    if (deviceID == null) {
        WifiManager wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        if (wm.isWifiEnabled()) {
            deviceID = wm.getConnectionInfo().getMacAddress();
        } else {/*from  w w  w . j  a  v  a2s . c om*/
            //fallback to ANDROID_ID - gets reset on data wipe, but it's better than nothing
            deviceID = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
    }
    deviceID = md5(deviceID);

    return deviceID;
}

From source file:com.kiandastream.musicplayer.MusicService.java

@Override
public void onCreate() {
    Log.i(TAG, "debug: Creating service");

    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare it.

    // create the Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above)

}

From source file:com.eastedge.readnovel.weibo.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from  w ww.  j  a va  2  s  . com*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.compal.telephonytest.TelephonyTest.java

public void test_2nd_BrowseWeb() {
    if (TelephonyBeTest) {
        Log.i(tag, "test_2nd_BrowseWeb start");
        testCaseId = getTestCaseId(tTelephonyBasicFunc, dBrowseWeb, sId);
        if (!isTelephonyManagerNull && !isContextNull && !isConnectivityManagerNull && !isIccCardNull) {
            mLog = "Browsing web";
            mWifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
            if (mWifiManager == null) {
                mLog = "mWifiManager == null";
            }/*from w w  w .ja  va2 s . co  m*/
            if (!turnOffWifi()) {
                mLog = "turn Off Wifi fail";
            }
            if (mConnectivityManager.getMobileDataEnabled()) {
                Log.i(tag, "Data already enabled");
                checkBrowseWeb();
            } else {
                if (enableDataEnabled(true)) {
                    Log.i(tag, "enableDataEnabled() true browse web");
                    checkBrowseWeb();
                } else {
                    Log.i(tag, "enableDataEnabled() fail browse web");
                    mLog = "enableDataEnabled() fail browse web";
                    outputResult(false, tTelephonyBasicFunc, dBrowseWeb, testCaseId);
                }
            }
        } else {
            mLog = "mTelephonyManager == null || context == null || isIccCardNull";
            outputResult(false, tTelephonyBasicFunc, dBrowseWeb, testCaseId);
        }
    }
}

From source file:cordova.plugins.Diagnostic.java

public void setWifiState(boolean enable) {
    WifiManager wifiManager = (WifiManager) this.cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
    if (enable && !wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(true);
    } else if (!enable && wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(false);
    }/*  ww  w  .j  a va2s  . co  m*/
}

From source file:com.sonymobile.dronecontrol.activity.MainActivity.java

private boolean verifyWifi() {
    boolean result = false;
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("WiFi").setMessage(R.string.DG_CONNECT_TO_WIFI)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override/*  w  w w.  ja  va 2  s .  co  m*/
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        dialog.dismiss();
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    } else {
        result = true;
    }
    return result;
}