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.heneryh.aquanotes.io.ApexExecutor.java

public void updateOutlet(Cursor cursor, String outletName, int position) throws HandlerException {

    /**/*  w  w  w  .  j a  va  2  s .  co  m*/
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    // Uhg, WifiManager stuff below crashes in AVD if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();
    String apexBaseURL;

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // oh, we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String pendingStateS = String.valueOf(position);
    nameValuePairs.add(new BasicNameValuePair(outletName + "_state", pendingStateS));

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

From source file:com.nd.android.u.square.service.MusicPlaybackService.java

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

    sInstance = this;

    // 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 Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else/* w ww  .java 2  s  .  c  o  m*/
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus

    mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.ic_square_notification_music_play);

    mMediaButtonReceiverComponent = new ComponentName(this, MusicIntentReceiver.class);

    MusicExecutor.getInstance().getEventBus().register(this);

    // ?
    MusicExecutor.getInstance().schedulePlayListUpdate(0L, 10L, TimeUnit.SECONDS);

    IntentFilter notificationIntentFilter = new IntentFilter();
    notificationIntentFilter.addAction(ACTION_STOP);
    registerReceiver(mNotificationIntentActionReceiver, notificationIntentFilter);
}

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

public void test_1st_DataEnabler() {
    if (TelephonyBeTest) {
        Log.i(tag, "test_1st_DataEnabler start");
        testCaseId = getTestCaseId(tTelephonyBasicFunc, dDataEnaler, sId);
        if (!isTelephonyManagerNull && !isConnectivityManagerNull && !isIccCardNull) {
            mLog = "Data Enabler";
            boolean nowStatus, checkDataEnabled, checkDataEnabledBar;
            mWifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
            if (mWifiManager == null) {
                mLog = "mWifiManager == null";
            }//from w  ww  .  j a v  a 2 s  .c o  m
            if (!turnOffWifi()) {
                mLog = "turn Off Wifi fail";
            }
            nowStatus = mConnectivityManager.getMobileDataEnabled();

            enableDataEnabled(!nowStatus);
            checkDataEnabled = enableDataEnabled(nowStatus);
            checkDataEnabledBar = enableDataEnabled(!nowStatus);
            if (nowStatus) {
                enableDataEnabled(nowStatus);
            }

            if (checkDataEnabled && checkDataEnabledBar && browseWeb()) {
                Log.i(tag, "test_1st_DataEnabler true");
                outputResult(true, tTelephonyBasicFunc, dDataEnaler, testCaseId);
            } else {
                Log.i(tag, "test_1st_DataEnabler false");
                outputResult(false, tTelephonyBasicFunc, dDataEnaler, testCaseId);
            }
        } else {
            mLog = "mTelephonyManager == null || isConnectivityManagerNull == null || isIccCardNull";
            outputResult(false, tTelephonyBasicFunc, dDataEnaler, testCaseId);
        }
    }
}

From source file:com.hijacker.InstallFirmwareDialog.java

void install(String firm_location, String util_location) {
    boolean start_airodump = false;
    if (getPIDs(PROCESS_AIRODUMP).size() > 0) {
        start_airodump = true;/*from w  w  w.ja  v a 2 s .  c o  m*/
        stop(PROCESS_AIRODUMP);
    }
    WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(false);
    if (debug)
        Log.d("HIJACKER/InstFirmware", "Backing up firmware from " + firm_location);
    if (backup_cb.isChecked()) {
        if (new File(firm_backup_file).exists()) {
            Toast.makeText(getActivity(), R.string.backup_exists, Toast.LENGTH_SHORT).show();
        } else {
            shell.run("cp -n " + firm_location + "fw_bcmdhd.bin " + firm_backup_file);
            Toast.makeText(getActivity(), R.string.backup_created, Toast.LENGTH_SHORT).show();
        }
    }
    shell.done(); //clear any existing output
    shell = Shell.getFreeShell();

    if (debug) {
        Log.d("HIJACKER/InstFirmware", "Installing firmware in " + firm_location);
        Log.d("HIJACKER/InstFirmware", "Installing utility in " + util_location);
    }
    shell.run(busybox + " mount -o rw,remount,rw /system");
    extract("fw_bcmdhd.bin", firm_location);
    extract("nexutil", util_location);
    shell.run(busybox + " mount -o ro,remount,ro /system");

    Toast.makeText(getActivity(), R.string.installed_firm_util, Toast.LENGTH_SHORT).show();
    wifiManager.setWifiEnabled(true);

    if (start_airodump)
        Airodump.startClean();
}

From source file:eu.operando.operandoapp.service.ProxyService.java

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override/*from w ww.j a v a  2 s  .  co m*/
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {
                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {
                                    String toReplace = responseFilter.getContent();
                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }
                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext)) {
                        return null;
                    }

                    //check for trusted access point
                    String ssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getSSID();
                    String bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getBSSID();
                    boolean trusted = false;
                    TrustedAccessPoint curr_tap = new TrustedAccessPoint(ssid, bssid);
                    for (TrustedAccessPoint tap : db.getAllTrustedAccessPoints()) {
                        if (curr_tap.isEqual(tap)) {
                            trusted = true;
                        }
                    }
                    if (!trusted) {
                        return getUntrustedGatewayResponse();
                    }

                    //check for blocked url

                    //check for exfiltration
                    requestFilterUtil = new RequestFilterUtil(getApplicationContext());
                    locationInfo = requestFilterUtil.getLocationInfo();
                    contactsInfo = requestFilterUtil.getContactsInfo();
                    IMEI = requestFilterUtil.getIMEI();
                    phoneNumber = requestFilterUtil.getPhoneNumber();
                    subscriberID = requestFilterUtil.getSubscriberID();
                    carrierName = requestFilterUtil.getCarrierName();
                    androidID = requestFilterUtil.getAndroidID();
                    macAdresses = requestFilterUtil.getMacAddresses();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfo = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }
                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = ((HttpRequest) request).uri(); //request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }
                    }

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();

                    if (httpObject instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();
                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (locationInfo.length > 0) {
                            //tolerate location miscalculation
                            float latitude = Float.parseFloat(locationInfo[0]);
                            float longitude = Float.parseFloat(locationInfo[1]);
                            Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(requestURI);
                            List<String> floats_in_uri = new ArrayList();
                            while (m.find()) {
                                floats_in_uri.add(m.group());
                            }
                            for (String s : floats_in_uri) {
                                if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                        || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                    exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                }
                            }
                        }
                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }
                        if (StringUtils.containsAny(requestURI, macAdresses)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                        }
                        if (requestURI.contains(IMEI) && !IMEI.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                        }
                        if (requestURI.contains(phoneNumber) && !phoneNumber.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                        }
                        if (requestURI.contains(subscriberID) && !subscriberID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                        }
                        if (requestURI.contains(carrierName) && !carrierName.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                        }
                        if (requestURI.contains(androidID) && !androidID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                        }
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            String contentStr = buf.toString(Charset.forName("UTF-8"));
                            if (locationInfo.length > 0) {
                                //tolerate location miscalculation
                                float latitude = Float.parseFloat(locationInfo[0]);
                                float longitude = Float.parseFloat(locationInfo[1]);
                                Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(contentStr);
                                List<String> floats_in_uri = new ArrayList();
                                while (m.find()) {
                                    floats_in_uri.add(m.group());
                                }
                                for (String s : floats_in_uri) {
                                    if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                            || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                        exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                    }
                                }
                            }
                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }
                            if (StringUtils.containsAny(contentStr, macAdresses)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                            }
                            if (contentStr.contains(IMEI) && !IMEI.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                            }
                            if (contentStr.contains(phoneNumber) && !phoneNumber.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                            }
                            if (contentStr.contains(subscriberID) && !subscriberID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                            }
                            if (contentStr.contains(carrierName) && !carrierName.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                            }
                            if (contentStr.contains(androidID) && !androidID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    //check exfiltrated list
                    if (!exfiltrated.isEmpty()) {
                        //retrieve all blocked and allowed domains
                        List<BlockedDomain> blocked = db.getAllBlockedDomains();
                        List<AllowedDomain> allowed = db.getAllAllowedDomains();
                        //get application name from app info
                        String appName = applicationInfo.replaceAll("\\(.+?\\)", "");
                        //check blocked domains
                        //if domain is stored as blocked, return a forbidden response
                        for (BlockedDomain b_dmn : blocked) {
                            if (b_dmn.info.equals(appName)) {
                                return getForbiddenRequestResponse(applicationInfo, exfiltrated);
                            }
                        }
                        //if domain is stored as allowed, return null for actual response
                        for (AllowedDomain a_dmn : allowed) {
                            if (a_dmn.info.equals(appName)) {
                                return null;
                            }
                        }
                        //get exfiltrated info to string array
                        String[] exfiltrated_array = new String[exfiltrated.size()];
                        int i = 0;
                        for (RequestFilterUtil.FilterType filter_type : exfiltrated) {
                            exfiltrated_array[i] = filter_type.name();
                            i++;
                        }
                        //retrieve all pending notifications
                        List<PendingNotification> pending = db.getAllPendingNotifications();
                        for (PendingNotification pending_notification : pending) {
                            //if pending notification includes specific app name and app permissions return response that a pending notification exists
                            if (pending_notification.app_info.equals(applicationInfo)) {
                                return getPendingResponse();
                            }
                        }
                        //if none pending notification exists, display a new notification
                        int notificationId = mainContext.getNotificationId();
                        mainContext.getNotificationUtil().displayExfiltratedNotification(getBaseContext(),
                                applicationInfo, exfiltrated, notificationId);
                        mainContext.setNotificationId(notificationId + 3);
                        //and update statistics
                        db.updateStatistics(exfiltrated);
                        return getAwaitingResponse();
                    }
                    return null;
                }
            };
        }
    };
}

From source file:ca.mcgill.hs.serv.LogFileUploaderService.java

@Override
public synchronized void onStart(final Intent intent, final int startId) {
    // Update the file list
    updateFileList();/* w  w  w .ja v a  2  s .  co m*/

    // If there are no files, return.
    if (fileList.size() == 0 && !started) {
        makeToast(getResources().getString(R.string.uploader_no_new_files), Toast.LENGTH_SHORT);
        return;
    }

    // If it was already started, return. Else, continue.
    if (started) {
        return;
    }

    // At this point we consider the service to be started.
    started = true;

    registerReceiver(wifiOnlyPrefChanged, new IntentFilter(WIFI_ONLY_CHANGED_INTENT));
    registerReceiver(autoPrefChanged, new IntentFilter(AUTO_UPLOAD_CHANGED_INTENT));

    wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiInfo = wifiMgr.getConnectionInfo();

    // Register completion receiver
    registerReceiver(completionReceiver, new IntentFilter(UPLOAD_COMPLETE_INTENT));

    // Connect to a network
    setUpConnection();

    notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_STRING);
    notificationMgr.cancel(NOTIFICATION_ID);

    final int icon = R.drawable.notification_icon;
    final String tickerText = getResources().getString(R.string.notification_ticker);
    final String contentTitle = getResources().getString(R.string.notification_upload_title);
    final String contentText = getResources().getString(R.string.notification_upload_text);

    final Notification n = new Notification(icon, tickerText, System.currentTimeMillis());

    final Intent i = new Intent(this, HSService.class);
    n.setLatestEventInfo(this, contentTitle, contentText,
            PendingIntent.getActivity(this.getBaseContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT));

    notificationMgr.notify(NOTIFICATION_ID, n);

    filesUploaded = 0;
    uploadFiles();
}

From source file:com.quran.labs.androidquran.service.AudioService.java

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

    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "audiolock");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // create the Audio Focus Helper, if the Audio Focus feature is available
    if (android.os.Build.VERSION.SDK_INT >= 8) {
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    }/*from w  w w .ja  v a  2s .c o  m*/
    // no focus feature, so we always "have" audio focus
    else {
        mAudioFocus = AudioFocus.Focused;
    }

    mMediaButtonReceiverComponent = new ComponentName(this, AudioIntentReceiver.class);
    mNotificationName = getString(R.string.app_name);

    mBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
}

From source file:com.android.development.Connectivity.java

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

    setContentView(R.layout.connectivity);

    mWm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mPm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mCm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
    mNetd = INetworkManagementService.Stub.asInterface(b);

    findViewById(R.id.enableWifi).setOnClickListener(mClickListener);
    findViewById(R.id.disableWifi).setOnClickListener(mClickListener);

    findViewById(R.id.startDelayedCycle).setOnClickListener(mClickListener);
    findViewById(R.id.stopDelayedCycle).setOnClickListener(mClickListener);
    mDCOnDurationEdit = (EditText) findViewById(R.id.dc_wifi_on_duration);
    mDCOnDurationEdit.setText(Long.toString(mDCOnDuration));
    mDCOffDurationEdit = (EditText) findViewById(R.id.dc_wifi_off_duration);
    mDCOffDurationEdit.setText(Long.toString(mDCOffDuration));
    mDCCycleCountView = (TextView) findViewById(R.id.dc_wifi_cycles_done);
    mDCCycleCountView.setText(Integer.toString(mDCCycleCount));

    findViewById(R.id.startScreenCycle).setOnClickListener(mClickListener);
    findViewById(R.id.stopScreenCycle).setOnClickListener(mClickListener);
    mSCOnDurationEdit = (EditText) findViewById(R.id.sc_wifi_on_duration);
    mSCOnDurationEdit.setText(Long.toString(mSCOnDuration));
    mSCOffDurationEdit = (EditText) findViewById(R.id.sc_wifi_off_duration);
    mSCOffDurationEdit.setText(Long.toString(mSCOffDuration));
    mSCCycleCountView = (TextView) findViewById(R.id.sc_wifi_cycles_done);
    mSCCycleCountView.setText(Integer.toString(mSCCycleCount));

    mScanButton = (Button) findViewById(R.id.startScan);
    mScanButton.setOnClickListener(mClickListener);
    mScanCyclesEdit = (EditText) findViewById(R.id.sc_scan_cycles);
    mScanCyclesEdit.setText(Long.toString(mScanCycles));
    mScanDisconnect = (CheckBox) findViewById(R.id.scanDisconnect);
    mScanDisconnect.setChecked(true);/* ww  w  .  j a  v a2s  .  co m*/
    mScanResults = (TextView) findViewById(R.id.sc_scan_results);
    mScanResults.setVisibility(View.INVISIBLE);

    mScanRecv = new WifiScanReceiver();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    findViewById(R.id.startTdls).setOnClickListener(mClickListener);
    findViewById(R.id.stopTdls).setOnClickListener(mClickListener);

    findViewById(R.id.start_mms).setOnClickListener(mClickListener);
    findViewById(R.id.stop_mms).setOnClickListener(mClickListener);
    findViewById(R.id.start_hipri).setOnClickListener(mClickListener);
    findViewById(R.id.stop_hipri).setOnClickListener(mClickListener);
    findViewById(R.id.crash).setOnClickListener(mClickListener);

    findViewById(R.id.add_default_route).setOnClickListener(mClickListener);
    findViewById(R.id.remove_default_route).setOnClickListener(mClickListener);
    findViewById(R.id.bound_http_request).setOnClickListener(mClickListener);
    findViewById(R.id.bound_socket_request).setOnClickListener(mClickListener);
    findViewById(R.id.routed_http_request).setOnClickListener(mClickListener);
    findViewById(R.id.routed_socket_request).setOnClickListener(mClickListener);
    findViewById(R.id.default_request).setOnClickListener(mClickListener);
    findViewById(R.id.default_socket).setOnClickListener(mClickListener);

    registerReceiver(mReceiver, new IntentFilter(CONNECTIVITY_TEST_ALARM));
}

From source file:fr.enseirb.odroidx.remote_client.MainActivity.java

public String getLocalIpAddress() {
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    String ipBinary = null;/*from  www  . j  a  v a  2  s.  c o  m*/
    try {
        ipBinary = Integer.toBinaryString(wm.getConnectionInfo().getIpAddress());
    } catch (Exception e) {
    }
    if (ipBinary != null) {
        while (ipBinary.length() < 32) {
            ipBinary = "0" + ipBinary;
        }
        String a = ipBinary.substring(0, 8);
        String b = ipBinary.substring(8, 16);
        String c = ipBinary.substring(16, 24);
        String d = ipBinary.substring(24, 32);
        String actualIpAddress = Integer.parseInt(d, 2) + "." + Integer.parseInt(c, 2) + "."
                + Integer.parseInt(b, 2) + "." + Integer.parseInt(a, 2);
        return actualIpAddress;
    } else {
        return null;
    }
}

From source file:com.odo.kcl.mobileminer.miner.MinerService.java

private void connectivityChanged() {
    String name = "None";
    ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = manager.getActiveNetworkInfo();
    if (netInfo != null) {
        if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
            switch (netInfo.getType()) {
            case ConnectivityManager.TYPE_WIFI:
                wifiData = true;//from  ww w . jav a 2 s  .c  om
                mobileData = false;
                if (!updating)
                    startUpdating();
                WifiManager wifiMgr = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                name = wifiInfo.getSSID();
                if (!networkName.equals(name)) {
                    wirelessData = new WifiData(wifiInfo);
                    MinerData helper = new MinerData(context);
                    helper.putWifiNetwork(helper.getWritableDatabase(), wirelessData, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                startScan(); // Always scan when we've got WIFI.
                //Log.i("MinerService","CONNECTED: WIFI");
                break;
            case ConnectivityManager.TYPE_MOBILE:
                wifiData = false;
                mobileData = true;
                if ("goldfish".equals(Build.HARDWARE)) {
                    if (!updating)
                        startUpdating();
                } else {
                    updating = false;
                }

                // https://code.google.com/p/android/issues/detail?id=24227
                //String name; Cursor c;
                //c = this.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null, null, null);
                //name = c.getString(c.getColumnIndex("name"));
                TelephonyManager telephonyManager = ((TelephonyManager) this
                        .getSystemService(Context.TELEPHONY_SERVICE));
                name = telephonyManager.getNetworkOperatorName();
                if (!networkName.equals(name)) {
                    MinerData helper = new MinerData(context);
                    helper.putMobileNetwork(helper.getWritableDatabase(), telephonyManager, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                //startScan();
                //Log.i("MinerService","CONNECTED MOBILE: "+name);
                break;
            default:
                //Log.i("MinerService",netInfo.getTypeName());
                break;
            }
        } else {
            scanning = false;
        }
    } else {
        scanning = false;
        networkName = "null";
    }

}