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.oo58.game.texaspoker.AppActivity.java

public static String getLocalMacAddress() {

    WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    return info.getMacAddress();

}

From source file:com.google.sample.castcompanionlibrary.utils.Utils.java

/**
 * Returns the SSID of the wifi connection, or <code>null</code> if there is no wifi.
 *
 * @param context/*from   w  w  w .java2 s.  c  o  m*/
 * @return
 */
public static String getWifiSsid(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (null != wifiInfo) {
        return wifiInfo.getSSID();
    }
    return null;
}

From source file:jackpal.androidterm.Term.java

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

    Log.v(TermDebug.LOG_TAG, "onCreate");

    mPrivateAlias = new ComponentName(this, RemoteInterface.PRIVACT_ACTIVITY_ALIAS);

    if (icicle == null)
        onNewIntent(getIntent());/*from w w  w.j a  v  a  2  s.co  m*/

    final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings = new TermSettings(getResources(), mPrefs);
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    boolean vimflavor = this.getPackageName().matches(".*vim.androidterm.*");

    if (!vimflavor && mSettings.doPathExtensions()) {
        mPathReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String path = makePathFromBundle(getResultExtras(false));
                if (intent.getAction().equals(ACTION_PATH_PREPEND_BROADCAST)) {
                    mSettings.setPrependPath(path);
                } else {
                    mSettings.setAppendPath(path);
                }
                mPendingPathBroadcasts--;

                if (mPendingPathBroadcasts <= 0 && mTermService != null) {
                    populateViewFlipper();
                    populateWindowList();
                }
            }
        };

        Intent broadcast = new Intent(ACTION_PATH_BROADCAST);
        if (AndroidCompat.SDK >= 12) {
            broadcast.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
        }
        mPendingPathBroadcasts++;
        sendOrderedBroadcast(broadcast, PERMISSION_PATH_BROADCAST, mPathReceiver, null, RESULT_OK, null, null);

        if (mSettings.allowPathPrepend()) {
            broadcast = new Intent(broadcast);
            broadcast.setAction(ACTION_PATH_PREPEND_BROADCAST);
            mPendingPathBroadcasts++;
            sendOrderedBroadcast(broadcast, PERMISSION_PATH_PREPEND_BROADCAST, mPathReceiver, null, RESULT_OK,
                    null, null);
        }
    }

    TSIntent = new Intent(this, TermService.class);
    startService(TSIntent);

    if (AndroidCompat.SDK >= 11) {
        int theme = mSettings.getColorTheme();
        int actionBarMode = mSettings.actionBarMode();
        mActionBarMode = actionBarMode;
        switch (actionBarMode) {
        case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo);
            } else {
                setTheme(R.style.Theme_Holo_Light);
            }
            break;
        case TermSettings.ACTION_BAR_MODE_HIDES + 1:
        case TermSettings.ACTION_BAR_MODE_HIDES:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo_ActionBarOverlay);
            } else {
                setTheme(R.style.Theme_Holo_Light_ActionBarOverlay);
            }
            break;
        }
    } else {
        mActionBarMode = TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE;
    }

    setContentView(R.layout.term_activity);
    mViewFlipper = (TermViewFlipper) findViewById(VIEW_FLIPPER);
    setFunctionKeyListener();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    int wifiLockMode = WifiManager.WIFI_MODE_FULL;
    if (AndroidCompat.SDK >= 12) {
        wifiLockMode = WIFI_MODE_FULL_HIGH_PERF;
    }
    mWifiLock = wm.createWifiLock(wifiLockMode, TermDebug.LOG_TAG);

    ActionBarCompat actionBar = ActivityCompat.getActionBar(this);
    if (actionBar != null) {
        mActionBar = actionBar;
        actionBar.setNavigationMode(ActionBarCompat.NAVIGATION_MODE_LIST);
        actionBar.setDisplayOptions(0, ActionBarCompat.DISPLAY_SHOW_TITLE);
        if (mActionBarMode >= TermSettings.ACTION_BAR_MODE_HIDES) {
            actionBar.hide();
        }
    }

    mHaveFullHwKeyboard = checkHaveFullHwKeyboard(getResources().getConfiguration());
    setSoftInputMode(mHaveFullHwKeyboard);

    if (mFunctionBar == -1)
        mFunctionBar = mSettings.showFunctionBar() ? 1 : 0;
    if (mFunctionBar == 1)
        setFunctionBar(mFunctionBar);

    updatePrefs();
    permissionCheckExternalStorage();
    mAlreadyStarted = true;
}

From source file:edu.drake.research.android.lipswithmaps.activity.MapsActivity.java

/**
 * get wifi scan//from w ww.j a  v a  2s.c o  m
 */
private void wifiScan() {
    if (mWifiManager == null) {
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }
    mWifiManager.startScan();
}

From source file:com.lofland.housebot.BotController.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.housebot);//from ww  w.j av  a2s.c om
    Log.d(TAG, "onCreate");

    /*
     * TODO: If you need to maintain and pass around context:
     * http://stackoverflow.com/questions/987072/using-application-context-everywhere
     */

    // Display start up toast:
    // http://developer.android.com/guide/topics/ui/notifiers/toasts.html
    Context context = getApplicationContext();
    CharSequence text = "ex Nehilo!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    // Display said toast
    toast.show();

    /*
     *  Turn on WiFi if it is off
     *  http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
     */
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    // Prevent keyboard from popping up as soon as app launches: (it works!)
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    /*
     * Keep the screen on, because as long as we are talking to the robot, this needs to be up http://stackoverflow.com/questions/9335908/how-to- prevent-the-screen-of
     * -an-android-device-to-turn-off-during-the-execution
     */
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    /*
     * One or more of these three lines sets the screen to minimum brightness, Which should extend battery drain, and be less distracting on the robot.
     */
    final WindowManager.LayoutParams winParams = this.getWindow().getAttributes();
    winParams.screenBrightness = 0.01f;
    winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;

    // The "Connect" screen has a "Name" and "Address box"
    // I'm not really sure what one puts in these, and if you leave them
    // empty it works fine.
    // So not 110% sure what to do with these. Can the text just be: ""?
    // Just comment these out, and run the command with nulls?
    // mName = (EditText) findViewById(R.id.name_edit);
    // mAddress = (EditText) findViewById(R.id.address_edit);
    // The NXT Remote Control app pops up a list of seen NXTs, so maybe I
    // need to implement that instead.

    // Text to speech
    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtSpeakText);

    // Now we need a Robot object before we an use any Roboty values!
    // We can pass defaults in or use the ones it provides
    myRobot = new Robot(INITIALTRAVELSPEED, INITIALROTATESPEED, DEFAULTVIEWANGLE);
    // We may have to pass this robot around a bit. ;)

    // Status Lines
    TextView distanceText = (TextView) findViewById(R.id.distanceText);
    distanceText.setText("???");
    TextView distanceLeftText = (TextView) findViewById(R.id.distanceLeftText);
    distanceLeftText.setText("???");
    TextView distanceRightText = (TextView) findViewById(R.id.distanceRightText);
    distanceRightText.setText("???");
    TextView headingText = (TextView) findViewById(R.id.headingText);
    headingText.setText("???");
    TextView actionText = (TextView) findViewById(R.id.isDoingText);
    actionText.setText("None");

    // Travel speed slider bar
    SeekBar travelSpeedBar = (SeekBar) findViewById(R.id.travelSpeed_seekBar);
    travelSpeedBar.setProgress(myRobot.getTravelSpeed());
    travelSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setTravelSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    // View angle slider bar
    SeekBar viewAngleBar = (SeekBar) findViewById(R.id.viewAngle_seekBar);
    viewAngleBar.setProgress(myRobot.getViewAngle());
    viewAngleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setViewAngle(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d(TAG, "View Angle Slider ");
            /*
             * If this gets sent every few milliseconds with the normal output, then there is no need to send a specific command every time it changes!
             */
            // sendCommandToRobot(Command.VIEWANGLE);
        }
    });

    // Rotation speed slider bar speedSP_seekBar
    SeekBar rotateSpeedBar = (SeekBar) findViewById(R.id.rotateSpeed_seekBar);
    rotateSpeedBar.setProgress(myRobot.getRotateSpeed());
    rotateSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setRotateSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    /*
     * This is where we find the four direction buttons defined So we could define ALL buttons this way, set up an ENUM with all options, and call the same function for ALL
     * options!
     * 
     * Just be sure the "release" only stops the robot on these, and not every button on the screen.
     * 
     * Maybe see how the code I stole this form does it?
     */
    Button buttonUp = (Button) findViewById(R.id.forward_button);
    buttonUp.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.FORWARD));
    Button buttonDown = (Button) findViewById(R.id.reverse_button);
    buttonDown.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.REVERSE));
    Button buttonLeft = (Button) findViewById(R.id.left_button);
    buttonLeft.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.LEFT));
    Button buttonRight = (Button) findViewById(R.id.right_button);
    buttonRight.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.RIGHT));

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });

    /*
     * This causes the typed text to be spoken when the Enter key is pressed.
     */
    txtText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                speakOut();
                return true;
            }
            return false;
        }
    });

    // Connect button
    connectToggleButton = (ToggleButton) findViewById(R.id.connectToggleButton);
    connectToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                Log.d(TAG, "Connect button Toggled On!");
                myRobot.setConnectRequested(true);
            } else {
                // The toggle is disabled
                Log.d(TAG, "Connect button Toggled OFF.");
                myRobot.setConnectRequested(false);
            }
        }
    });

    if (nxtStatusMessageHandler == null)
        nxtStatusMessageHandler = new StatusMessageHandler();

    mStatusThread = new StatusThread(context, nxtStatusMessageHandler);
    mStatusThread.start();

    // Start the web service!
    Log.d(TAG, "Start web service here:");
    // Initiate message handler for web service
    if (robotWebServerMessageHandler == null)
        robotWebServerMessageHandler = new WebServerMessageHandler(this); // Has to include "this" to send context, see WebServerMessageHandler for explanation

    robotWebServer = new WebServer(context, PORT, robotWebServerMessageHandler, myRobot);

    try {
        robotWebServer.start();
    } catch (IOException e) {
        Log.d(TAG, "robotWebServer failed to start");
        //e.printStackTrace();
    }

    // TODO:
    /*
     * See this reference on how to rebuild this handler in onCreate if it is gone: http://stackoverflow.com/questions/18221593/android-handler-changing-weakreference
     */
    // TODO - Should I stop this thread in Destroy or some such place?

    Log.d(TAG, "Web service was started.");

}

From source file:com.xdyou.sanguo.GameSanGuo.java

protected void onCreate(Bundle savedInstanceState) {
    Log.d("SGAPP", "onCreate");
    mActivity = this;
    super.onCreate(savedInstanceState);

    //AppsFlyerSDK initial 2015.1.12
    AppsFlyerLib.setAppsFlyerKey("6HRzTLQfzQHGBQ87KzZttH");
    //? AppsFlyer
    AppsFlyerLib.sendTracking(getApplicationContext());

    //GA sdk ?//from  ww w  .j av  a  2  s.c o  m
    GameAnalytics.initialise(this, GA_SCR_KEY, GA_GAME_KEY);
    GameAnalytics.startSession(this);

    //MM: AdvertiserSDK 2014.11.26
    Tracker.conversionTrack(this, "zywx_sgyxlm_hk_mo_tw");

    //??
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // ========================?TalkingData 
    Log.d("SGAPP", "talkingdataAppid || " + talkingDataAppId);
    TalkingDataGA.init(this, talkingDataAppId, talkingDataChannelId);
    // ========================?TalkingData 

    // ===================Facebook ?
    // ??session
    this.createFBSession();
    // Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    // ===================Facebook ?

    //GoCPA
    GocpaUtil.setAppId(GOCPA_APPID);
    GocpaUtil.setAdvertiserId(GOCPA_ADVID);
    GocpaUtil.setReferral(false);

    GocpaTracker.getInstance(this).reportDevice();

    // ==================Go2Play listener_Begin_=======================================
    TradeService.setOnBalanceChangedListener(new ICallback() {
        @Override
        public void onResult(boolean isSuccess, Bundle bundle, Throwable ths) {
            // ???
            if (isSuccess) {
                Log.e("go2play", "Charged Success!");
                Log.e("go2play", "Balance: " + TradeService.getBalance(false));
            }
        }

    });
    // ==================Go2Play listener_End_=========================================

    // ==================ChartBoost SDK _Begin_============================================

    // ?chartboost
    this.cb = Chartboost.sharedChartboost();

    // chartboostappIdappKey, sdk????
    final String appIdCB = "54af952a43150f627b0fbb4a";
    final String appSignatureCB = "bea16683ef974c0393cf55c41719ef694ae8a0d5";

    this.cb.onCreate(this, appIdCB, appSignatureCB, null);

    // ==================ChartBoost SDK_End_==============================================

    // ==================hasoffers _Begin_============================================
    MobileAppTracker.init(getApplicationContext(), "24078", "3fba6dcf91bc7251866e59278574f16a");
    mobileAppTracker = MobileAppTracker.getInstance();

    // Collect Google Play Advertising ID
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());

                mobileAppTracker.setGoogleAdvertisingId(adInfo.getId(), adInfo.isLimitAdTrackingEnabled());
            } catch (IOException e) {

            } catch (GooglePlayServicesNotAvailableException e) {
                mobileAppTracker.setAndroidId(Secure.getString(getContentResolver(), Secure.ANDROID_ID));
            } catch (GooglePlayServicesRepairableException e) {
                // Encountered a recoverable error connecting to Google Play
                // services.
            }
        }
    }).start();

    // For collecting Android ID, device ID, and MAC address
    // Before August 1st 2014, remove these calls - only Google AID should
    // be collected.
    mobileAppTracker.setAndroidId(Secure.getString(getContentResolver(), Secure.ANDROID_ID));
    String deviceId = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    mobileAppTracker.setDeviceId(deviceId);
    try {
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mobileAppTracker.setMacAddress(wm.getConnectionInfo().getMacAddress());
    } catch (NullPointerException e) {
        System.out.println("NullPointerExp");
    }

    // ==================hasoffers  _End_===========================

    // ?? ?Handler????????facebook?
    handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case FB_LOGIN:
                fbLogin();
                break;
            case FB_LOGOUT:
                fbLogout();
                break;
            case FB_SHARE: {
                // ?????????
                String imageName = msg.obj.toString();
                fbShareContent(imageName);
            }
                break;
            case FB_CREATE_SESSION: {
                createFBSession();
            }
                break;
            case GOTO_GOOGLE_PLAY: {
                enterGooglePlay();
            }
                break;
            case BUID_DIALOG: {
                buildDialog();
            }
                break;
            case HANDLER_OPEN_URL: {
                execOpenUrl((String) msg.obj);
            }
                break;
            case APP_FLYERS_LOGIN: {
                appFlyersTrackerLogin((String) msg.obj);
            }
                break;
            case MSG_SHOW_TOAST: {
                handleShowToast((String) msg.obj);
            }
                break;
            case MSG_SET_USER_DATA: {
                handleSetUserData((SgUserData) msg.obj);
            }
                break;
            default:
                Log.e("facebook", "error come out!");
                System.out.println("oh shit!");
                break;
            }
        }
    };

}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;/*from w w w.j  a va  2  s. co m*/

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.example.multi_ndef.Frag_Write.java

private void initListener() {

    mWriteTagButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            initialize();/* w w w.  j ava 2s  .c om*/
            // TODO Auto-generated method stub
            network_name = ma.getWifiNetwork();
            password = ma.getWifiPassword();
            WifiManager wifi;

            String t;
            wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            List<ScanResult> results;
            results = wifi.getScanResults();
            String bssid = null;
            for (ScanResult result : results) {

                if ((network_name).equals(result.SSID)) {
                    bssid = result.BSSID;
                    break;
                }

            }

            String delimiter = ":";
            /*
             * given string will be split by the argument delimiter
             * provided.
             */
            mac_add = bssid.split(delimiter);
            /* print substrings */

            net_length = network_name.length();

            pass_length = password.length();

            Toast toast = Toast.makeText(getApplicationContext(), "Keep tag near the phone",
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
            toast.show();

            getSMS();
            getMail();
            getLocation();
            getTelephone();

            enableWriteMode();

        }

    });

}

From source file:com.zzl.zl_app.cache.Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*from w w w.  j  a  v  a 2 s  . c o  m*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
        // ??APN?
        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;
}