Trouble in Enabling and Disabling services in Android - android

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" />

Related

Mobile Hotspot on and off Android on Marshmallow

I want turn on or off Mobile Hotspot by pressing a button On or button Off .I have written this code for setOnClickListner and Given Permission in Manifest File.But i am not able to turn on Mobile Hotspot.I just want to turn mobile hotspot On without any configuration of hotspot or mobile data.My android Os version is Marshmellow.
btnHotspotOn.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressLint("WifiManagerLeak")
public void onClick(View v) {
try {
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class,
Boolean.TYPE);
method.setAccessible(true);
boolean enable =true;
WifiConfiguration configuration = null;
method.invoke(manager, configuration, enable);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
});
Following is the Manifest File:-
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

time out issues with Android Multicast

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);
}
}
}

How to turn wifi off and on progarmatically? [duplicate]

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"/>

android turn screen off and on

I've made a simple application to turn the screen on and off once a button is pressed, the code does not present any error but it doesn't do anything. Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#SuppressLint("Wakelock")
#Override
public void onClick(View arg0) {
Log.d(TAG, String.valueOf(screenWakeLock));
if (screenWakeLock != null) {
if(screenWakeLock.isHeld())
Log.d(TAG, "wavelock held");
screenWakeLock.release();
screenWakeLock = null;
}else{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "screenWakeLock");
screenWakeLock.acquire();
Log.d(TAG, String.valueOf(screenWakeLock));
}
}
});
}
and the permissions in the manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.DEVICE_POWER"></uses-permission>
There's no error, but nothing happens on the screen. Does anyone know why?
Thank you in advance!
In another question:
Programmatically switching off Android phone
I found a way that works. After rooting you phone:
try {
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "reboot -p" });
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}

How to create access point programmatically

I've written the code to create an access point for android devices. I've tested on both emulator and real device.But it doesn't work. Where did i get wrong?
public class MainWAP extends Activity {
WifiManager wifiManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wap);
}
public void openWifi(View v) {
createWifiAccessPoint();
}
private void createWifiAccessPoint() {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods();
boolean methodFound = false;
for (Method method: wmMethods) {
if (method.getName().equals("setWifiApEnabled")) {
methodFound = true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "AccessPoint";
netConfig.allowedAuthAlgorithms.set(
WifiConfiguration.AuthAlgorithm.OPEN);
try {
boolean apstatus = (Boolean) method.invoke(
wifiManager, netConfig, true);
for (Method isWifiApEnabledmethod: wmMethods) {
if (isWifiApEnabledmethod.getName().equals(
"isWifiApEnabled")) {
while (!(Boolean) isWifiApEnabledmethod.invoke(
wifiManager)) {};
for (Method method1: wmMethods) {
if (method1.getName().equals(
"getWifiApState")) {
int apstate;
apstate = (Integer) method1.invoke(
wifiManager);
}
}
}
}
if (apstatus) {
Log.d("Splash Activity",
"Access Point created");
} else {
Log.d("Splash Activity",
"Access Point creation failed");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if (!methodFound) {
Log.d("Splash Activity",
"cannot configure an access point");
}
}
}
Your WiFiManager is definately not initialized.
In your onCreate method add this:
wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
You need few things to make this code to work.
1) Init wifiManager onCreate() :
WifiManager wifiManager = (WiFiManager) getSystemService(Context.WIFI_SERVICE);
2) You need to ask for this permissions in you AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />
3) Your application need to be signed with system certificates.
With your method of exploiting undocumented APIs using reflection, things might not work well in all scenarios.
Well, you can try adding these in your manifest file and give a try.
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.WRITE_APN_SETTINGS

Categories

Resources