This question already has answers here:
Android: How to Enable/Disable Wifi or Internet Connection Programmatically
(10 answers)
Closed 8 years ago.
I am designing an app which needs to turn off and then on with in one/two seconds (at first installation (only once) ). Is there anyway to do this automatically by programming.
Is there any problem to other apps in same mobile if we turn off wifi for 1 sec like is it affects any downloads from other app?
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.start_wifi);
stop = (Button) findViewById(R.id.stop_wifi);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
WifiManager wifi = (WifiManager) MainActivity.this
.getSystemService(Context.WIFI_SERVICE);
if (!wifi.isWifiEnabled()) {
wifi.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "Turn ON WIFI",
Toast.LENGTH_LONG).show();
}
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
WifiManager wifi = (WifiManager) MainActivity.this
.getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()) {
wifi.setWifiEnabled(false);
Toast.makeText(MainActivity.this, "Turn OFF WIFI",
Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
Log.v("MainActivity Exception", Log.getStackTraceString(e));
}
}
In Manifest
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Related
So my aim main is to make an app that can send messages from one phone to another without any internet connectivity. So as a first step I tried to create an app to switch wifi On/Off and show the available wifi devices. The app seems to work fine on emulator but does not work on the phone. Even the basic toggling of wifi didn't work on the phone. I've attached my MainActivity.java file. Kindly help.
MainActivity.java:-
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
TextView wifiStatusTextView;
TextView wifiListView;
Switch wifiSwitch;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Defining Variables
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiStatusTextView = (TextView) findViewById(R.id.wifi_status_text_view);
wifiListView = (TextView) findViewById(R.id.wifi_list);
wifiSwitch = (Switch) findViewById(R.id.wifi_switch);
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
/* Checking wifi state.
* If wifi is enabled, display "wifi is on" and set toggle button to on position.
* If Wifi is disabled, display "wifi is off" and set toggle button to off position.
*/
if (wifiManager.isWifiEnabled()) {
wifiStatusTextView.setText("Wifi is currently ON");
wifiSwitch.setChecked(true);
} else {
wifiStatusTextView.setText("Wifi is currently OFF");
wifiSwitch.setChecked(false);
}
/* adds listener to toggle button
* If toggle is checked, wifi is enabled and "Wifi is on" is displayed.
* If toggle is unchecked, wifi is enabled and "Wifi is off" is displayed.
*/
wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
wifiManager.setWifiEnabled(true);
wifiStatusTextView.setText("Wifi is currently ON");
Toast.makeText(MainActivity.this, "Wifi may take a moment to turn on", Toast.LENGTH_LONG).show();
} else {
wifiManager.setWifiEnabled(false);
wifiStatusTextView.setText("Wifi is currently OFF");
}
}
});
}
#Override
public void onResume()
{
super.onResume();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 87);
}
}
}
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult> mScanResults = wifiManager.getScanResults();
sb = new StringBuilder();
wifiList = wifiManager.getScanResults();
for (int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ".");
sb.append((wifiList.get(i)).SSID);
sb.append("\n");
}
wifiListView.setText(sb);
}
}
};
}
I am working on an Android app that will receive multicast packets from a network that already outputs reliable multicast data on 239.255.x.x . I have verified that my device can receive multicast with another application. I'm new to Java and Android but I did confirm that my original code to gather the Multicast info worked in a java application and have been struggling to get everything working in the Android side of things. I have permissions set in the manifest,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
the networking portion of code runs in an Asynctask as to not crash the app but my Multicast.receive() calls all result in a time out.Is there something else I am missing or something that prevents multicast sockets from working in the asynctask class?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new getACN.execute();
}
});
}
public class getACN extends AsyncTask<Void, Void, String> {
#Override
public String doInBackground(Void... Void) {
byte[] buf = new byte[1000];
try {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifiManager.createMulticastLock("sACN");
multicastLock.acquire();
InetAddress group = InetAddress.getByName("239.255.0.3");
DatagramPacket recv = new DatagramPacket(buf,buf.length);
MulticastSocket sock = new MulticastSocket(5568);
sock.joinGroup(group);
sock.setSoTimeout(1000);
sock.receive(recv);
sock.leaveGroup(group);
} catch (IOException e) {
return e.getMessage();
} catch (SecurityException e) {
return e.getMessage();
}
return Arrays.toString(buf);
}
#Override
protected void onPostExecute(String result){
TextView textView = (TextView) findViewById(R.id.text01);
textView.setText(result);
}
}
}
I'm new to android app. I want to read data from my arduino Uno R3 and display it on my app using a serial cable and an OTG adapter.
Although, I can't get my UsbManager to recognized my device. So when I try to set up a connection, it always fail.
Here's the part of my code where I initiate everything.
public UsbManager = mUsbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_depth);
setupActionBar();
textView = (TextView) findViewById(R.id.textView2);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
button = (Button) findViewById(R.id.buttonStart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView.setText("Bravo");
updateDevice();
if (mRunning == true) {
receiveThread();
}
}
});
}
public void updateDevice() {
Intent intent= getIntent();
String action = intent.getAction();
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null){
Toast.makeText(this, "Initialisation 1", Toast.LENGTH_SHORT).show();
initDevice(device);
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
Toast.makeText(this, "Initialisation", Toast.LENGTH_SHORT).show();
initDevice(device);
} else {
initDevice(null);
}
}
(...) //Obviously, this is not in my code!!
private boolean initDevice(UsbDevice device) {
mConnection = mUsbManager.openDevice(device);
if (mConnection == null) {
if (DEBUG) Log.e(TAG, "Opening USB device failed!");
Toast.makeText(DisplayDepth.this, "open failed", Toast.LENGTH_SHORT).show();
return false;
}
And it always fail here ( I get the toast msg "open failed" ).
I add to my manifest what it takes so my arduino r3 is recognized and a connection message is always shown when I plug it into my phone.... Need help!!!
Thanks
I want to make some scan of the Access Points, but the method wifiManager.startScan() doesn't work in my code :
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonMeasure:
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
registerReceiver(broadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.setWifiEnabled(true); //Edit
timer2 = new Timer(WifiActivity.this);
while(broadcastReceiver.getMeasureFinished()<=49){
Log.d("info7","mesure" + broadcastReceiver.getMeasureFinished());
success = false;
while(success==false){
success=wifiManager.startScan();
Log.d("info2","startScan : " + success);
}
}
case R.id.buttonLocate:
//localization.
}
}
Eclipse is well enter in the loop, but doesn't want to read wifiManager.startScan();, what is the cause? Thanks!
I am new to Android development and have trouble enabling / disabling the wifi & audio services. I get the appropriate manager instance using the getSystemService method. But I don't get any error when enabling wifi using:
wifiMgr.setWifiEnabled(true);
But the wifi is simply not turned on! Similarly I use
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
or
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
But the phone doesn't go to silent mode! Here is my complete code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
final ToggleButton bt = (ToggleButton)findViewById(R.id.bluetooth_button);
final ToggleButton wf = (ToggleButton)findViewById(R.id.wifi_button);
final ToggleButton sb = (ToggleButton)findViewById(R.id.sound_button);
// Check Audio
AudioManager mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
soundStatus = mAudio.getRingerMode();
if(soundStatus == AudioManager.RINGER_MODE_NORMAL)
sb.setChecked(true);
// Check WiFi
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiStatus = wifiMgr.isWifiEnabled();
if(wifiStatus)
wf.setChecked(true);
sb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
TextView tv = (TextView) findViewById(R.id.result);
AudioManager mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
if(sb.isChecked()) {
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
tv.setText("Ringer set to Normal");
} else {
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
tv.setText("Ringer set to Silent");
}
}catch (Exception e) {
e.printStackTrace();
}
}
});
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
TextView tv = (TextView) findViewById(R.id.result);
if(bt.isChecked())
tv.setText("Bluetooth is On!");
else
tv.setText("Bluetooth is Off!");
} catch (Exception e) {
e.printStackTrace();
}
}
});
wf.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
TextView tv = (TextView) findViewById(R.id.result);
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(wf.isChecked()) {
wifiMgr.setWifiEnabled(true);
tv.setText("Wifi is On!");
} else {
wifiMgr.setWifiEnabled(false);
tv.setText("Wifi is Off!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}catch (Exception e) {
e.printStackTrace();
}
}
I have added the following permissions:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
I am using Motorola milestone (android 2.1).. What Am I missing? can anybody point me what is wrong with this code?
Thanks in Advance for suggestions and corrections.
The Issue was solved by added more permissions!
For people who are facing the same issue, you will have to add the following permissions as well:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
Now, In addition to these I needed Audio and Bluetooth access. for that I had to add:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BLUETOOTH" />