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.sentaroh.android.SMBExplorer.FileIo.java

@SuppressWarnings("deprecation")
@Override/*from ww  w.  ja v  a  2 s .  c  om*/
public void run() {
    sendLogMsg("I", "Task has started.");

    final WakeLock wake_lock = ((PowerManager) mContext.getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
    //                         | PowerManager.ON_AFTER_RELEASE
                    , "SMBExplorer-ScreenOn");
    final WifiLock wifi_lock = ((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "SMBExplorer-wifi");

    if (mGp.fileIoWakeLockRequired)
        wake_lock.acquire();
    if (mGp.fileIoWifiLockRequired)
        wifi_lock.acquire();

    try {
        if (fileIoArea == null)
            fileIoArea = new byte[SMB_BUFF_SIZE];//4096*64];

        taskBeginTime = System.currentTimeMillis();

        waitMediaScanner(true);

        boolean fileioTaskResultOk = false;
        for (int i = 0; i < fileioLinkParm.size(); i++) {
            fileioTaskResultOk = fileOperation(fileioLinkParm.get(i));
            if (!fileioTaskResultOk)
                break;
        }
        sendLogMsg("I", "Task was ended. fileioTaskResultOk=" + fileioTaskResultOk + ", fileioThreadCtrl:"
                + fileioThreadCtrl.toString());
        sendLogMsg("I", "Task elapsed time=" + (System.currentTimeMillis() - taskBeginTime));
        if (fileioTaskResultOk) {
            fileioThreadCtrl.setThreadResultSuccess();
            sendDebugLogMsg(1, "I", "Task was endeded without error.");
        } else if (fileioThreadCtrl.isEnabled()) {
            fileioThreadCtrl.setThreadResultError();
            sendLogMsg("W", "Task was ended with error.");
        } else {
            fileioThreadCtrl.setThreadResultCancelled();
            sendLogMsg("W", "Task was cancelled.");
        }
        fileioThreadCtrl.setDisabled();
        mediaScanner.disconnect();
        waitMediaScanner(false);

        uiHandler.post(new Runnable() {// UI thread
            @Override
            public void run() {
                notifyEvent.notifyToListener(true, null);
            }
        });
    } finally {
        if (wake_lock.isHeld())
            wake_lock.release();
        if (wifi_lock.isHeld())
            wifi_lock.release();
    }
}

From source file:de.j4velin.wifiAutoOff.Preferences.java

@SuppressWarnings("deprecation")
@Override//  w ww  . j a v  a 2  s  . c  om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    if (BuildConfig.DEBUG && PermissionChecker.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    status = (StatusPreference) findPreference("status");
    status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(final Preference preference) {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            boolean connected = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            if (wm.isWifiEnabled() && !connected) {
                try {
                    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            } else if (!wm.isWifiEnabled()) {
                wm.setWifiEnabled(true);
            } else {
                try {
                    startActivity(
                            new Intent(Settings.ACTION_WIFI_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        }
    });

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final CheckBoxPreference screen_off = (CheckBoxPreference) findPreference("off_screen_off");
    screen_off.setSummary(
            getString(R.string.for_at_least, prefs.getInt("screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF)));

    if (!keepWiFiOn(this)) {
        screen_off.setChecked(false);
    }

    screen_off.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (!keepWiFiOn(Preferences.this)) {
                    new AlertDialog.Builder(Preferences.this).setMessage(R.string.sleep_policy)
                            .setPositiveButton(R.string.adv_wifi_settings, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    } catch (Exception e) {
                                        Toast.makeText(Preferences.this, R.string.settings_not_found_,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).setNegativeButton(android.R.string.cancel, new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return false;
                }
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, screen_off,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, screen_off, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "screen_off_timeout",
                            Receiver.TIMEOUT_SCREEN_OFF, false);
                }
            }
            return true;
        }
    });

    findPreference("off_no_network").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, preference,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "no_network_timeout", Receiver.TIMEOUT_NO_NETWORK, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, preference, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "no_network_timeout",
                            Receiver.TIMEOUT_NO_NETWORK, false);
                }
            }
            return true;
        }
    });

    final CheckBoxPreference on_at = (CheckBoxPreference) findPreference("on_at");
    on_at.setTitle(getString(R.string.at_summary, prefs.getString("on_at_time", Receiver.ON_AT_TIME)));
    on_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("on_at_time", Receiver.ON_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("on_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        on_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        on_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_on_at_));
                dialog.show();
            }
            return true;
        }
    });

    final CheckBoxPreference off_at = (CheckBoxPreference) findPreference("off_at");
    off_at.setTitle(getString(R.string.at_summary, prefs.getString("off_at_time", Receiver.OFF_AT_TIME)));
    off_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("off_at_time", Receiver.OFF_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("off_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        off_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        off_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_off_at_));
                dialog.show();
            }
            return true;
        }
    });

    final Preference on_every = findPreference("on_every");
    final String[] time_names = getResources().getStringArray(R.array.time_names);
    // default 2 hours
    on_every.setTitle(getString(R.string.every_summary, prefs.getString("on_every_str", time_names[4])));
    on_every.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Preferences.this);
                builder.setTitle(R.string.turn_wifi_on_every).setItems(time_names,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                prefs.edit().putInt("on_every_time_min", time_values[which])
                                        .putString("on_every_str", time_names[which]).commit();
                                on_every.setTitle(getString(R.string.every_summary, time_names[which]));
                            }
                        });
                builder.create().show();
            }
            return true;
        }
    });

    Preference locations = findPreference("locations");
    if (BuildConfig.FLAVOR.equals("play")) {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)) {
            locations.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    startActivity(new Intent(Preferences.this, Locations.class));
                    return true;
                }
            });
        } else {
            locations.setEnabled(false);
        }
    } else {
        locations.setSummary("Not available in F-Droid version");
        locations.setEnabled(false);
    }

    final Preference power = findPreference("power_connected");
    power.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((boolean) newValue) {
                Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                if (battery != null && battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0) {
                    // already connected to external power
                    prefs.edit().putBoolean("ignore_screen_off", true).commit();
                }
            } else {
                prefs.edit().putBoolean("ignore_screen_off", false).commit();
            }
            return true;
        }
    });
}

From source file:net.majorkernelpanic.spydroid.ui.HandsetFragment.java

public void displayIpAddress() {
    WifiManager wifiManager = (WifiManager) SpydroidApplication.getContext()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    String ipaddress = null;//from   w w w  .j a v a2 s . co m
    Log.d("SpydroidActivity", "getNetworkId " + info.getNetworkId());
    if (info != null && info.getNetworkId() > -1) {
        int i = info.getIpAddress();
        String ip = String.format(Locale.ENGLISH, "%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff,
                i >> 24 & 0xff);
        mLine1.setText("http://");
        mLine1.append(ip);
        mLine1.append(":" + SpydroidApplication.sHttpPort);
        mLine2.setText("rtsp://");
        mLine2.append(ip);
        mLine2.append(":" + SpydroidApplication.sRtspPort);
        streamingState(0);
    } else if ((ipaddress = Utilities.getLocalIpAddress(true)) != null) {
        mLine1.setText("http://");
        mLine1.append(ipaddress);
        mLine1.append(":" + SpydroidApplication.sHttpPort);
        mLine2.setText("rtsp://");
        mLine2.append(ipaddress);
        mLine2.append(":" + SpydroidApplication.sRtspPort);
        streamingState(0);
    } else {
        mLine1.setText("HTTP://xxx.xxx.xxx.xxx:" + SpydroidApplication.sHttpPort);
        mLine2.setText("RTSP://xxx.xxx.xxx.xxx:" + SpydroidApplication.sHttpPort);
        streamingState(2);
    }
}

From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java

/** Called when the activity is first created. */
@Override//  w  w w .ja va 2s. co m
public void onCreate(Bundle savedInstanceState) {
    //      StrictMode.enableDefaults();
    //      setTheme(android.R.style.Theme_Dialog);
    //      setTheme(android.R.style.Theme_Holo_Light);
    //      setTheme(android.R.style.Theme_Light);
    super.onCreate(savedInstanceState);
    //      requestWindowFeature(Window.FEATURE_NO_TITLE);

    mCurrentLocal = getResources().getConfiguration().locale;

    setContentView(R.layout.main);
    mContext = this;
    mGp = (GlobalParameters) getApplication();
    mGp.enableMainUi = true;
    mGp.uiHandler = new Handler();
    mGp.SMBSync_External_Root_Dir = LocalMountPoint.getExternalStorageDir();

    startService(new Intent(mContext, SMBSyncService.class));

    mDimScreenWakelock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    //                    PowerManager.PARTIAL_WAKE_LOCK
                    | PowerManager.ACQUIRE_CAUSES_WAKEUP
    //                         | PowerManager.ON_AFTER_RELEASE
                    , "SMBSync-ScreenOn");

    mWifiLock = ((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "SMBSync-wifi");

    if (tcService == null)
        tcService = new ThreadCtrl();

    //      if (Build.VERSION.SDK_INT>=14)
    //         this.getActionBar().setHomeButtonEnabled(false);

    if (util == null)
        util = new SMBSyncUtil(this.getApplicationContext(), "Main", mGp);
    util.setActivityIsForeground(true);

    if (ccMenu == null)
        ccMenu = new CustomContextMenu(getResources(), getSupportFragmentManager());
    commonDlg = new CommonDialog(mContext, getSupportFragmentManager());

    createTabView();
    loadMsgString();
    initSettingsParms();
    applySettingParms();
    initJcifsOption();

    checkExternalStorage();
    mGp.SMBSync_Internal_Root_Dir = getFilesDir().toString();

    util.openLogFile();

    initAdapterAndView();

    util.addDebugLogMsg(1, "I", "onCreate entered, " + "resartStatus=" + restartStatus
            + ", isActivityForeground=" + util.isActivityForeground());

    getApplVersionName();

    if (profMaint == null)
        profMaint = new ProfileMaintenance(util, this, commonDlg, ccMenu, mGp);

    SchedulerMain.setTimer(mContext, SCHEDULER_INTENT_SET_TIMER_IF_NOT_SET);
}

From source file:by.zatta.pilight.connection.ConnectionService.java

private boolean addedToPreferences() {
    String currentNetwork = null;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (!(info == null)) {
        // Log.d(TAG, "networkInfo: " + info.getExtraInfo());
        currentNetwork = info.getExtraInfo();
    }/*from   w w  w  .  ja va2  s .c om*/
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (!(wifiInfo == null)) {
        // Log.d(TAG, "wifiInfo:" + wifiInfo.getSSID());
        currentNetwork = wifiInfo.getSSID();
    }
    if (currentNetwork == null)
        return false;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(aCtx);
    String previous = prefs.getString("networks_known", "");
    // Log.d(TAG, previous);
    currentNetwork = currentNetwork.replace("\"", "");
    if (previous.contains(currentNetwork)) {
        // Log.d(TAG, previous + " did contain " + currentNetwork);
        return false;
    } else {
        previous = previous + "|&|" + currentNetwork;
        // Log.d(TAG, previous);
        Editor edit = prefs.edit();
        edit.putString("networks_known", previous);
        edit.commit();
        return true;
    }
}

From source file:it.unipr.ce.dsg.gamidroid.activities.NAM4JAndroidActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

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

    context = this;

    isTablet = Utils.isTablet(this);

    // Setting the default network
    sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
    Editor editor = sharedPreferences.edit();
    editor.putString(Constants.NETWORK, Constants.DEFAULT_NETWORK);
    editor.commit();/* ww  w.  ja v a 2 s. c o m*/

    // Starting the resources monitoring service
    startService(new Intent(this, DeviceMonitorService.class));

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    // Settings menu elements
    ArrayList<MenuListElement> listElements = new ArrayList<MenuListElement>();

    listElements.add(new MenuListElement(getResources().getString(R.string.connectMenuTitle),
            getResources().getString(R.string.connectMenuSubTitle)));
    listElements.add(new MenuListElement(getResources().getString(R.string.settingsMenuTitle),
            getResources().getString(R.string.settingsMenuSubTitle)));
    listElements.add(new MenuListElement(getResources().getString(R.string.exitMenuTitle),
            getResources().getString(R.string.exitMenuSubTitle)));

    listView = (ListView) findViewById(R.id.ListViewContent);

    MenuListAdapter adapter = new MenuListAdapter(this, R.layout.menu_list_view_row, listElements);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new ListItemClickListener());

    mainRL = (RelativeLayout) findViewById(R.id.rlContainer);
    listRL = (RelativeLayout) findViewById(R.id.listContainer);

    cpuBar = (LinearLayout) findViewById(R.id.CpuBar);
    memoryBar = (LinearLayout) findViewById(R.id.MemoryBar);

    titleBarRL = (RelativeLayout) findViewById(R.id.titleLl);

    // Adding swipe gesture listener to the top bar
    titleBarRL.setOnTouchListener(new SwipeAndClickListener());

    menuButton = (Button) findViewById(R.id.menuButton);
    menuButton.setOnTouchListener(new SwipeAndClickListener());

    infoButton = (Button) findViewById(R.id.infoButton);
    infoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlertDialog dialog = new AlertDialog(NAM4JAndroidActivity.this) {

                @Override
                public boolean dispatchTouchEvent(MotionEvent event) {
                    dismiss();
                    return false;
                }

            };

            String text = getResources().getString(R.string.aboutApp);
            String title = getResources().getString(R.string.nam4j);

            dialog.setMessage(text);
            dialog.setTitle(title);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
    });

    centerButton = (Button) findViewById(R.id.centerButton);
    centerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            centerMap();
        }
    });

    isTablet = Utils.isTablet(context);

    int[] screenSize = Utils.getScreenSize(context, getWindow());
    screenWidth = screenSize[0];
    screenHeight = screenSize[1];

    // Updates the display orientation each time the device is rotated
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        screenOrientation = Orientation.LANDSCAPE;
    } else {
        screenOrientation = Orientation.PORTRAIT;
    }

    // If the device is portrait, the menu button is displayed, the menu is
    // hidden and the swipe listener is added to the menu bar
    if (screenOrientation == Orientation.PORTRAIT) {

        menuButton.setVisibility(View.VISIBLE);

        // Adding swipe gesture listener to the top bar
        titleBarRL.setOnTouchListener(new SwipeAndClickListener());

        if (isTablet) {
            menuWidth = 0.35;
        } else {
            menuWidth = 0.6;
        }
    } else {
        // If the device is a tablet in landscape, the menu button is
        // hidden, the menu is displayed, the swipe listener is not added to
        // the menu bar and the mainRL width is set to the window's width
        // minus the menu's width
        if (isTablet) {
            menuWidth = 0.2;
            menuButton.setVisibility(View.INVISIBLE);

            RelativeLayout.LayoutParams menuListLP = (LayoutParams) mainRL.getLayoutParams();

            // Setting the main view width as the container width without
            // the menu
            menuListLP.width = (int) (screenWidth * (1 - menuWidth));
            mainRL.setLayoutParams(menuListLP);

            displaySideMenu();
        } else {
            menuWidth = 0.4;
            menuButton.setVisibility(View.VISIBLE);

            // Adding swipe gesture listener to the top bar
            titleBarRL.setOnTouchListener(new SwipeAndClickListener());
        }
    }

    // Check if the device has the Google Play Services installed and
    // updated. They are necessary to use Google Maps
    int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);

    if (code != ConnectionResult.SUCCESS) {

        showErrorDialog(code);

        System.out.println("Google Play Services error");

        FrameLayout fl = (FrameLayout) findViewById(R.id.frameId);
        fl.removeAllViews();
    } else {
        // Create a new global location parameters object
        mLocationRequest = new LocationRequest();

        // Set the update interval
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        bitmapDescriptorBlue = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);

        blueCircle = BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.blue_circle));

        bitmapDescriptorRed = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);

        // Create a new location client, using the enclosing class to handle
        // callbacks
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapview)).getMap();

        if (map != null) {

            // Set default map center and zoom on Parma
            double lat = 44.7950156;
            double lgt = 10.32547;
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lgt), 12.0f));

            // Adding listeners to the map respectively for zoom level
            // change and onTap event
            map.setOnCameraChangeListener(getCameraChangeListener());
            map.setOnMapClickListener(getOnMapClickListener());

            // Set map type as normal (i.e. not the satellite view)
            map.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL);

            // Hide traffic layer
            map.setTrafficEnabled(false);

            // Enable the 'my-location' layer, which continuously draws an
            // indication of a user's current location and bearing, and
            // displays UI controls that allow the interaction with the
            // location itself
            // map.setMyLocationEnabled(true);

            ml = new HashMap<String, Marker>();

            // Get file manager for config files
            fileManager = FileManager.getFileManager();
            fileManager.createFiles();

            map.setOnMarkerClickListener(this);

        } else {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("The map cannot be initialized.");
            dialog.setCancelable(true);
            dialog.setPositiveButton(getResources().getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            dialog.show();
        }
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Enable multicast networking", example = "")
@APIParam(params = { "boolean" })
public void setMulticast(boolean b) {
    WifiManager wifi = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    if (wifi != null) {
        if (b) {//w  w w  .j  av  a2  s. c o m
            wifiLock = wifi.createMulticastLock("mylock");
            wifiLock.acquire();
        } else {
            wifiLock.release();
        }
    }
}

From source file:com.carreygroup.JARVIS.MyApplication.java

public void CreateListener() {
    if (demon.Connected()) {
        try {/*from   w  ww  .  j a  va  2s  . c  o  m*/
            ThreadRun = true;
            if (m_ReceiverThread != null)
                m_ReceiverThread.interrupt();
            if (m_DetectorTHread != null)
                m_DetectorTHread.interrupt();

            if ((getEthnetMode() == Ethnet.TCP) || (getEthnetMode() == Ethnet.P2P)) {
                m_DetectorTHread = new Thread(m_Detector);
                m_ReceiverThread = new Thread(m_TCP_Receiver);
                m_ReceiverThread.start();
                m_DetectorTHread.start();
            }

            if (getEthnetMode() == Ethnet.UDP) {
                try {
                    wifimanager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                    m_DetectorTHread = new Thread(m_Detector);
                    m_ReceiverThread = new Thread(m_UDP_Receiver);
                    m_ReceiverThread.start();
                    m_DetectorTHread.start();
                } catch (Exception e) {
                    // TODO: handle exception
                    Log.e("_DEBUG", "WIFI UDP,UDP!");
                    Toast.makeText(mHomeActivity, "WIFI UDP,UDP!",
                            Toast.LENGTH_SHORT).show();
                }
            }
            //mThreadClient = new Thread(mRunnable);  
        } catch (Exception e) {
            Toast.makeText(mHomeActivity, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}

From source file:com.google.android.libraries.cast.companionlibrary.utils.Utils.java

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

From source file:com.zrlh.llkc.funciton.Http_Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * //ww w.  j av a  2 s  .c  om
 * @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, Http_Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Http_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;
}