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:at.maui.cheapcast.service.CheapCastService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "onCreate()");

    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mNetIf = Utils.getWifiNetworkInterface(mWifiManager);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mPreferences = getSharedPreferences("cheapcast", MODE_PRIVATE | MODE_MULTI_PROCESS);
    } else {/*from ww w. j a  v a  2 s  . c  o m*/
        mPreferences = getSharedPreferences("cheapcast", MODE_PRIVATE);
    }
    Log.d(LOG_TAG, String.format("Starting up: friendlyName: %s",
            mPreferences.getString("friendly_name", "CheapCasto")));
    mGson = new Gson();

    mGoogleAnalytics = GoogleAnalytics.getInstance(this);
    mGaTracker = mGoogleAnalytics.getTracker(getString(R.string.ga_trackingId));
    mGoogleAnalytics.setAppOptOut(mPreferences.getBoolean("analytics", false));

    Thread.UncaughtExceptionHandler myHandler = new ExceptionReporter(mGaTracker, // Currently used Tracker.
            GAServiceManager.getInstance(), // GAServiceManager singleton.
            Thread.getDefaultUncaughtExceptionHandler(), this); // Current default uncaught exception handler.

    mGaTracker.sendEvent("CheapCastService", "ServiceStart", null, null);

    mRegisteredApps = new HashMap<String, App>();
    registerApp(new App("ChromeCast", "https://www.gstatic.com/cv/receiver.html?$query"));
    registerApp(new App("YouTube", "https://www.youtube.com/tv?$query"));
    registerApp(new App("PlayMovies", "https://play.google.com/video/avi/eureka?$query",
            new String[] { "play-movies", "ramp" }));
    registerApp(new App("GoogleMusic", "https://play.google.com/music/cast/player"));

    registerApp(new App("GoogleCastSampleApp", "http://anzymrcvr.appspot.com/receiver/anzymrcvr.html"));
    registerApp(new App("GoogleCastPlayer", "https://www.gstatic.com/eureka/html/gcp.html"));
    registerApp(new App("Fling", "$query"));
    registerApp(new App("TicTacToe", "http://www.gstatic.com/eureka/sample/tictactoe/tictactoe.html",
            new String[] { "com.google.chromecast.demo.tictactoe" }));
}

From source file:com.collectme.cordova.diagnostic.Diagnostic.java

public boolean isWifiEnabled() {
    WifiManager wifiManager = (WifiManager) this.cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
    boolean result = wifiManager.isWifiEnabled();
    return result;
}

From source file:com.google.android.gms.samples.vision.face.facetracker.MainActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/* w w w.  ja  va  2  s.  com*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainactivity);

    //        ---Ambil username dari sharedpreference agar user tetap dapat melihat schedule jika keluar dari apps------
    sharedPreferences = getSharedPreferences("PHAROS", MODE_PRIVATE);
    username = sharedPreferences.getString("Username", "");
    //        ---------------------------------------------------------------------------------------------------------

    //        ---Deklarasi fragment fragment yang akan di gunakan---
    Fragment CameraFragment = new CameraFragment();
    Fragment LoginFramgent = new LoginFragment();
    Fragment ScheduleFragment = new ScheduleFragment();
    //        -----------------------------------------------------

    //        Meminta permisssion untuk GPS jika menggunakan android Marshmallow keatas
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION }, 1);
    }
    //        -------------------------------------------------------------------------

    //       ------- Instantiasi intent filter untuk broadcast recevier------
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    IntentFilter connectionIntentFilter = new IntentFilter();
    connectionIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    //        ---------------------------------------------------------------------

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiConfiguration = new WifiConfiguration();

    //        Registrasikan broadcast receiver
    registerReceiver(new wifiEnabled(wifiManager), intentFilter);
    registerReceiver(new wifiConnecting(wifiManager), connectionIntentFilter);
    //        ---------------------------------------

    //       -------- Deklarasi view pager---------
    viewPager = (ViewPager) findViewById(R.id.fragmentFrame);
    pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), CameraFragment, LoginFramgent,
            ScheduleFragment);
    viewPager.setAdapter(pagerAdapter);
    //        Mengarahkan halaman awal saat membuka aplikasi ke fragment index 1
    viewPager.setCurrentItem(1);
    //        -------------------------------------

}

From source file:info.tongrenlu.music.LocalPlayback.java

public LocalPlayback(MusicService service) {
    this.mService = service;
    this.mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    this.mWifiLock = ((WifiManager) service.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, MusicService.TAG);
}

From source file:eu.power_switch.gui.dialog.AddSsidDialog.java

@NonNull
@Override//from   w  w w.  j a va2  s .c  o m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ArrayList<String> connections = new ArrayList<>();

            for (ScanResult scanResult : mainWifi.getScanResults()) {
                if (scanResult.SSID != null && !scanResult.SSID.isEmpty()) {
                    connections.add(scanResult.SSID);
                }
            }

            updateSSIDs(connections);

            layoutLoading.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }
    };

    mainWifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    contentView = inflater.inflate(R.layout.dialog_add_ssid, null);
    builder.setView(contentView);

    editText_ssid = (TextInputEditText) contentView.findViewById(R.id.editText_ssid);
    editText_ssid.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            checkValidity();
        }
    });

    final IconicsImageView refresh = (IconicsImageView) contentView.findViewById(R.id.button_refresh);
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mainWifi.isWifiEnabled()) {
                refresh.startAnimation(AnimationHandler.getRotationClockwiseAnimation(getContext()));
                refreshSsids();
            } else {
                Toast.makeText(getActivity(), "WiFi disabled!", Toast.LENGTH_LONG).show();
            }
        }
    });

    layoutLoading = (LinearLayout) contentView.findViewById(R.id.layoutLoading);

    listView = (ListView) contentView.findViewById(R.id.listView);
    ssidAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_multiple_choice, ssids);
    listView.setAdapter(ssidAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            checkValidity();
        }
    });

    builder.setTitle(R.string.add_ssids);
    builder.setPositiveButton(R.string.add, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                sendSsidAddedBroadcast(getContext(), getSelectedSSIDs());
            } catch (Exception e) {
                StatusMessageHandler.showErrorMessage(getTargetFragment().getView().findViewById(R.id.listView),
                        e);
            }
        }
    });

    builder.setNeutralButton(android.R.string.cancel, null);

    setPositiveButtonVisibility(false);

    dialog = builder.create();
    dialog.setCanceledOnTouchOutside(false); // prevent close dialog on touch outside window
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    dialog.show();

    defaultTextColor = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).getTextColors()
            .getDefaultColor();

    checkValidity();

    refreshSsids();

    return dialog;
}

From source file:com.sdsoft.motoactv_export.WebActivity.java

public boolean promptforWifi() {
    if (!isOnline(false)) {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.getWifiState() != 3) {
            new AlertDialog.Builder(this).setTitle("Enable WiFi.")
                    .setMessage("Internet connection needed, would you like to enable WiFi?")
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                            wifiManager.setWifiEnabled(true);
                            //UpdateUtil.EnableWifi(getBaseContext());
                        }//w  w  w .  j  a  v a  2 s .com
                    }).setNegativeButton(android.R.string.no, null).show();
        }
    }
    return true;
}

From source file:com.classiqo.nativeandroid_32bitz.playback.LocalPlayback.java

public LocalPlayback(Context context, MusicProvider musicProvider) {
    this.mContext = context;
    this.mMusicProvider = musicProvider;
    this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    this.mWifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "nA_32bitz_lock");
    this.mState = PlaybackStateCompat.STATE_NONE;
}

From source file:net.geniecode.ttr.ScheduleReceiver.java

@SuppressWarnings("deprecation")
@SuppressLint({ "Recycle", "NewApi", "InlinedApi" })
@Override//  w  ww.  ja  v  a  2  s .c  o  m
public void onReceive(Context context, Intent intent) {
    if (!Schedules.SCHEDULE_ACTION.equals(intent.getAction())) {
        // Unknown intent, bail.
        return;
    }

    Schedule schedule = null;
    // Grab the schedule from the intent. Since the remote AlarmManagerService
    // fills in the Intent to add some extra data, it must unparcel the
    // Schedule object. It throws a ClassNotFoundException when unparcelling.
    // To avoid this, do the marshalling ourselves.
    final byte[] data = intent.getByteArrayExtra(Schedules.SCHEDULE_RAW_DATA);
    if (data != null) {
        Parcel in = Parcel.obtain();
        in.unmarshall(data, 0, data.length);
        in.setDataPosition(0);
        schedule = Schedule.CREATOR.createFromParcel(in);
    }

    if (schedule == null) {
        // Make sure we set the next schedule if needed.
        Schedules.setNextSchedule(context);
        return;
    }

    // Disable this schedule if it does not repeat.
    if (!schedule.daysOfWeek.isRepeatSet()) {
        Schedules.enableSchedule(context, schedule.id, false);
    } else {
        // Enable the next schedule if there is one. The above call to
        // enableSchedule will call setNextSchedule so avoid calling it twice.
        Schedules.setNextSchedule(context);
    }

    long now = System.currentTimeMillis();

    if (now > schedule.time + STALE_WINDOW) {
        return;
    }

    // Get telephony service
    mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    // Execute only for devices with versions of Android less than 4.2
    if (android.os.Build.VERSION.SDK_INT < 17) {
        // Get flight mode state
        boolean isEnabled = Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;

        // Get Wi-Fi service
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Enable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Get Wi-Fi state and disable that one too, just in case
            // (On some devices it doesn't get disabled when the flight mode is
            // turned on, so we do it here)
            boolean isWifiEnabled = mWifiManager.isWifiEnabled();

            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);

            if (isWifiEnabled) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
                mWifiManager.setWifiEnabled(false);
            } else {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        } else if ((!schedule.aponoff) && (isEnabled) && (schedule.mode.equals("1"))) {
            // Disable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Restore previously remembered Wi-Fi state
            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
            Boolean WiFiState = settings.getBoolean(WIFI_STATE, true);

            if (WiFiState) {
                mWifiManager.setWifiEnabled(true);
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        }
        // Check whether there are ongoing phone calls, and if so
        // show notification instead of just enabling the flight mode
        else if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
        // Execute for devices with Android 4.2   or higher
    } else {
        // Get flight mode state
        String result = Settings.Global.getString(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON);

        if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((!schedule.aponoff) && (result.equals("1")) && (schedule.mode.equals("1"))) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
    }

    // Get audio service
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // Get current ringer mode and set silent or normal mode accordingly
    switch (mAudioManager.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        // If the phone is set to vibrate let's make it completely silent
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        // or restore the regular sounds on it if that's scheduled
        else if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    }
}

From source file:mobisocial.musubi.ui.NearbyActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nearby);

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

    findViewById(R.id.qr).setOnClickListener(new OnClickListener() {
        @Override/* ww w  .  j a va 2 s .  co  m*/
        public void onClick(View v) {
            IntentIntegrator.initiateScan(NearbyActivity.this);
        }
    });
    findViewById(R.id.qr).setVisibility(View.GONE);
    findViewById(R.id.go).setVisibility(View.GONE);

    DBG = MusubiBaseActivity.isDeveloperModeEnabled(this);
    setTitle("Nearby");
    mAdapter = new NearbyAdapter(this, R.layout.nearby_groups_item, mNearbyList);

    ListView lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(mAdapter);
    lv.setOnItemClickListener(this);

    if (true) {
        findViewById(R.id.social).setVisibility(View.GONE);
    } else {
        setupMulticastScanner();
    }
    EditText tv = (EditText) findViewById(R.id.password);
    tv.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            synchronized (NearbyActivity.this) {
                mNearbyList.clear();
                mAdapter.notifyDataSetChanged();
            }
            scanNearby();
        }
    });

    if (savedInstanceState == null) {
        UsageMetrics.getUsageMetrics(this).report(MusubiMetrics.VISITED_NEARBY);
    }

    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider == null || !provider.contains("gps") || !provider.contains("network")) {
        new AlertDialog.Builder(this).setTitle("Location Settings").setMessage(
                "You should enable both network-based and GPS-based location services to ensure you can find nearby groups.")
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).setPositiveButton("Go to Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        } catch (Throwable t) {
                            Log.e(TAG, "failed to launch location settings", t);
                        }
                    }
                }).show();
    }
}