I have a web app (secured via SSL) that has an access to camera.It shows camera captures in a canvas. It worked perfectly in the browser. However, I want the camera content to show in the Webview in my app.
Here is my code in the method onCreate:
final WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("https://myvideoapp.me");
myWebView.setWebViewClient(new WebViewClient());
Here is permissions i used in my manifest.XML
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
You'll need to ask permission if you're coding android +4.4
Into your MainActivity, inside your class, use this if you want to ask for CAMERA permission:
private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 0;
private boolean checkAndRequestPermissions() {
int permission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
List listPermissionsNeeded = new ArrayList();
if (permission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, (String[]) listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
And also you have to check it inside your onCreate void function like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkAndRequestPermissions()) {
return;
}
.........
Related
I am trying to make the "Take photo" tutorial from here and after following all the steps I still have an error. More exactly after I take the picture it displays the message "camera has stopped". I added a button that opens the camera on click and an imageView to display the photo. I am trying to deploy the app on Samsung Galaxy S7 (Android 8.0.0,API 26).
This is the setOnClickListener:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById((R.id.button));
ImageView imageView = (ImageView)findViewById(R.id.imageView);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
button.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
And this is the methos for camera:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File imageView = null;
try {
imageView = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (imageView != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.camapp.fileprovider",
imageView);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
The file path:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="Android/data/com.example.camapp/files/Pictures" />
</paths>
And the permission:
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Provider:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.camapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
And i have the same method for onActivityResult() createImageFile() and galleryAddPic() from the tutorial.
Here is the stacktrace:
java.lang.IllegalStateException: #NotNull method com/android/tools/idea/gradle/project/model/AndroidModuleModel.getRootDir must not return null
at com.android.tools.idea.gradle.project.model.AndroidModuleModel.$$$reportNull$$$0(AndroidModuleModel.java)
at com.android.tools.idea.gradle.project.model.AndroidModuleModel.getRootDir(AndroidModuleModel.java:571)
at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.findContentEntries(ContentRootsModuleSetupStep.java:71)
at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.doSetUpModule(ContentRootsModuleSetupStep.java:58)
at com.android.tools.idea.gradle.project.sync.setup.module.android.ContentRootsModuleSetupStep.doSetUpModule(ContentRootsModuleSetupStep.java:41)
at com.android.tools.idea.gradle.project.sync.setup.module.ModuleSetupStep.setUpModule(ModuleSetupStep.java:35)
at com.android.tools.idea.gradle.project.sync.setup.module.common.BaseSetup.setUpModule(BaseSetup.java:41)
at com.android.tools.idea.gradle.project.sync.ng.ModuleSetup.setupModuleModels(ModuleSetup.java:141)
at com.android.tools.idea.gradle.project.sync.ng.CachedProjectModelsSetup.setUpModules(CachedProjectModelsSetup.java:116)
at com.android.tools.idea.gradle.project.sync.ng.ProjectSetup$ProjectSetupImpl.setUpProject(ProjectSetup.java:82)
at com.android.tools.idea.gradle.project.sync.ng.SyncResultHandler.onSyncSkipped(SyncResultHandler.java:164)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.trySyncWithCachedGradleModels(NewGradleSync.java:219)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.sync(NewGradleSync.java:165)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync.access$000(NewGradleSync.java:59)
at com.android.tools.idea.gradle.project.sync.ng.NewGradleSync$2.run(NewGradleSync.java:151)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:736)
at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:157)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:580)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:525)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:85)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:144)
at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:395)
at com.intellij.openapi.application.impl.ApplicationImpl$1.run(ApplicationImpl.java:314)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I want to make a button that opens the camera take a picture and save it in the gallery or other specified directory because I will make some image processing on that photo.I tried almost all the tutorials on yt and I really had a hard time finding a solution for this problem.I appreciate any solution or suggestion you have.Thank you for you're time!
If your app requires the camera to click a picture, the CAMERA permission should be asked
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.CAMERA"/>
<!-- other permissions go here -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application ...>
...
</application>
Your app should then prompt user to grant the camera & storage permissions
if (ContextCompat.checkSelfPermission(YourActivityName.this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
YOUR_PERMISSIONS_REQUEST_CODE);
// YOUR_PERMISSIONS_REQUEST_CODE is an
// app-defined int constant. The callback method gets the
// result of the request.
} else {
// Permission has already been granted
}
Also define the file provider in manifest file
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yourPackageName.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_list"></meta-data>
</provider>
I should generate a .pdf file inside the android data folder to use the Java code below, with the permissions enabled in the XML manifest file. But when I run the code I have the following exception. The application has different permissions within the manifest, It should all be configured correctly, I state that the application I'm testing on an old Android 4. How can I solve this? and what is it due to?
Exception: error: java. I. FileNotFoundException: /data/my.pdf:
open failed: EACCES (Permission denied)
Code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE " />
public static Boolean GeneratePDF(String base64) {
Boolean ret = true;
try {
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + "my.pdf");
byte[] pdfAsBytes = Base64.decode(base64, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
} catch (Exception ex) {
System.out.println("\n Errore Generazione File: "+ex);
ret = false;
}
return ret;
}
you have to give Write permission at run time.
It can be achieved something as following...
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
private static final int REQUEST_WRITE_PERMISSION = 111;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GeneratePDF("your String name");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
} else {
GeneratePDF("your String name");
}
}
}
Replace this line
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
To:
String direttorio= Environment.getExternalStorageDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + my.pdf");
if you're using Android 6.0 and above,
there could be 2 ways:
1 if you're making only for demo purpose you can manually give permission to app
by going in settings->apps->permissions. Then allow all permission which are
required.
2 you've to implement runtime permissions so that user can allow it runtime.
Whenever I try to use a Wi-Fi Scan for Android Wear, I always get no results from the scan. The code that I use works for my mobile device, but with Android Wear, it always returns an empty list. Code is as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
mContainerView = (BoxInsetLayout) findViewById(R.id.container);
mTextView = (TextView) findViewById(R.id.text);
mClockView = (TextView) findViewById(R.id.clock);
test = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mTextView.setVisibility(View.VISIBLE);
if (test.isWifiEnabled() == false)
{
test.setWifiEnabled(true);
}
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
Log.w("myApp", "received");
List<ScanResult> results = test.getScanResults();
int j = 0;
int myArray1[] = new int[results.size()];
String myArray2[] = new String[results.size()];
for (ScanResult result : results) {
//toPrint+= " " + result.BSSID + " " + result.level + "\n";
myArray1[j] = result.level;
myArray2[j] = result.BSSID;
j++;
if (j > 20) {
break;
}
}
Button test2;
test2 = (Button) findViewById(R.id.tLight);
test2.setText("Test: " + Integer.toString(results.size()));
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 0x12345);
}
test.startScan();
}
The following permissions are also enabled in the manifest file:
<uses-feature android:name="android.hardware.type.watch" />
<uses-feature android:name="android.hardware.wifi" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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.CHANGE_WIFI_STATE" />
I am developing an App to check Wifi points.
I am getting error "java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results" at wifiManager.getScanResults() even though I already declared those permissions.
main activity
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
String[] wifis;
WifiReceiver wifiReceiver;
ListView wifiListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiListView = (ListView) findViewById(R.id.wifi_list);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WifiReceiver();
wifiManager.startScan();
}
protected void onPause() {
unregisterReceiver(wifiReceiver);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
private class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> wifiScanList = wifiManager.getScanResults();
wifis = new String[wifiScanList.size()];
for (int i = 0; i < wifiScanList.size(); i++) {
wifis[i] = wifiScanList.get(i).toString();
}
wifiListView.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, wifis));
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I am on SDK 6.0
I observed similar question, but solution does not apply since I already declared permission.
Anyone know what might be problem? Thank you.
In Android M, you need to ask for the permission which is defined as dangerous in PermissionModel to the user before start using each time, it as such:
private boolean mayRequestLocation() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
Snackbar.make(mView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
});
} else {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
return false;
}
Add this to your Activity:
private static final int REQUEST_FINE_LOCATION=0
and load it during runtime with:
loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
To evaluate the results of your permission request, you can override onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// The requested permission is granted.
}
else{
// The user disallowed the requested permission.
}
return;
}
}
MADAO is right: you should turn on GPS to get the WIFI access point list.
But I'm not sure about PEERS_MAC_ADDRESS. If you look at the source code (line 957):
/**
* Return the results of the most recent access point scan, in the form of
* a list of {#link ScanResult} objects.
* #return the list of results
*/
public List<ScanResult> getScanResults(String callingPackage) {
enforceAccessPermission();
int userId = UserHandle.getCallingUserId();
int uid = Binder.getCallingUid();
boolean canReadPeerMacAddresses = checkPeersMacAddress();
boolean isActiveNetworkScorer =
NetworkScorerAppManager.isCallerActiveScorer(mContext, uid);
boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
long ident = Binder.clearCallingIdentity();
try {
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !isLocationEnabled()) {
return new ArrayList<ScanResult>();
}
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !checkCallerCanAccessScanResults(callingPackage, uid)) {
return new ArrayList<ScanResult>();
}
if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
!= AppOpsManager.MODE_ALLOWED) {
return new ArrayList<ScanResult>();
}
if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
return new ArrayList<ScanResult>();
}
return mWifiStateMachine.syncGetScanResultsList();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
The first if is checking canReadPeerMacAddresses which the code for checkPeersMacAddress() is:
/**
* Returns true if the caller holds PEERS_MAC_ADDRESS.
*/
private boolean checkPeersMacAddress() {
return mContext.checkCallingOrSelfPermission(
android.Manifest.permission.PEERS_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
}
If you add the permission you can bypass if (!canReadPeerMacAddresses && !isActiveNetworkScorer && !isLocationEnabled()) {. I've tested but I cannot get WIFI MAC list by just using the permission and disabling location.
ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION is necessary. To get a valid result, you also have to turn on GPS or get a PEERS_MAC_ADDRESS permission like Setting.
I want to enable/disable wifi from my Android application. How can I do that?
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false); // true or false to activate/deactivate wifi
You also need to request the permission in your AndroidManifest.xml :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
To enable/disable WiFi in your application you need to use WiFiManager class. Create an Object of WiFiManager class to get the services of WiFi.
WifiManager wifi;
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);//Turn off Wifi
wifi.setWifiEnabled(true);//Turn on Wifi
And you have to put the following permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
To get the whole sample code of enable/disable Wifi in android with UI visit this website
try this code
Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(gpsOptionsIntent,0);
To enable/disable wifi from an app in Android Q (Android 10) use Settings Panel:
val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
startActivityForResult(panelIntent, 0)
On previous versions of Android this should work (appropriate permissions should be added to AndroidManifest file, see answers above):
(context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
Resulting code might look something like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
startActivityForResult(panelIntent, 0)
} else {
(context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}
Where context is a reference to android.content.Context object.
try this
public void disableWifi(Context context, Boolean bool) {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(bool)
wifi.setWifiEnabled(false);
else
wifi.setWifiEnabled(true);
}
public class MainActivity extends AppCompatActivity {
Switch btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Switch) findViewById(R.id.switch1);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggleWiFi(true);
Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!", Toast.LENGTH_LONG).show();
} else {
toggleWiFi(false);
Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!", Toast.LENGTH_LONG).show();
}
}
});
}
public void toggleWiFi(boolean status){
WifiManager wifiManager = (WifiManager)this.getSystemService(WIFI_SERVICE);
if (status && !wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
} else if (!status && wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}
Add User Permission in Manifest Files