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" />
Related
I am testing my app on android 10 and I try to gain r/w access to all files.
I tried to follow this Solution but I still can't get the MANAGE_EXTERNAL_STORAGE permission.
I also tried this Solution 2.
On my manifest I ask for:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
<application
android:name=".GlobalVars"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.HangMan">
class Permissions extends Application{
public String Name;
public String ManifestName;
public boolean IsGranted;
Permissions(String name, String manifestName){
Name = name;
ManifestName = manifestName;
IsGranted = false;
}
Permissions(String name, String manifestName, boolean isGranted){
Name = name;
ManifestName = manifestName;
IsGranted = isGranted;
}
}
When the app is create is check the permissions and is the permissions are not granted the user has to accept them.
I use this code:
Define the required permission globally:
public class GlobalVars extends Application {
public static List<Permissions> AppPermissions = Arrays.asList(
new Permissions("MANAGE_EXTERNAL_STORAGE", Manifest.permission.MANAGE_EXTERNAL_STORAGE),
new Permissions("READ_EXTERNAL_STORAGE", Manifest.permission.READ_EXTERNAL_STORAGE),
new Permissions("WRITE_EXTERNAL_STORAGE", Manifest.permission.WRITE_EXTERNAL_STORAGE),
new Permissions("READ_SMS", Manifest.permission.READ_SMS),
new Permissions("SEND_SMS", Manifest.permission.SEND_SMS),
new Permissions("ACCESS_BACKGROUND_LOCATION", Manifest.permission.ACCESS_BACKGROUND_LOCATION),
new Permissions("CAMERA", Manifest.permission.CAMERA),
new Permissions("RECORD_AUDIO", Manifest.permission.RECORD_AUDIO),
new Permissions("WRITE_CONTACTS", Manifest.permission.WRITE_CONTACTS),
new Permissions("READ_CONTACTS", Manifest.permission.READ_CONTACTS),
new Permissions("RECORD_AUDIO", Manifest.permission.READ_CALL_LOG)
);
}
in my MainActivity:
protected void onStart() {
mPermissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
#Override
public void onActivityResult(Map<String, Boolean> result) {
for(Permissions permission: GlobalVars.AppPermissions){
if (result.get(permission.ManifestName) != null) {
permission.IsGranted = result.get(permission.ManifestName);
}
}
}
});
if(Build.VERSION.SDK_INT >= 30) {
if (Environment.isExternalStorageManager()){
}else{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
requestPermission();
super.onStart();
}
private void requestPermission() {
// A simple check of whether runtime permissions need to be managed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> permissionRequest = new ArrayList<String>();
for(Permissions permission: GlobalVars.AppPermissions){
int pp = ContextCompat.checkSelfPermission(MainActivity.this, permission.ManifestName);
int pg = PackageManager.PERMISSION_GRANTED;
if (ContextCompat.checkSelfPermission(MainActivity.this, permission.ManifestName) != PackageManager.PERMISSION_GRANTED) {
permissionRequest.add(permission.ManifestName);
}
}
if (!permissionRequest.isEmpty()){
mPermissionResultLauncher.launch(permissionRequest.toArray(new String[0]));
}
}
}
The above code works well and pops up the required requested permissions if they are nor granted.
However, when I check, e.g.:
int me = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.MANAGE_EXTERNAL_STORAGE);
int re = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
int we = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
After granting all the permissions MANAGE_EXTERNAL_STORAGE always return -1.
My app as I noticed has not r/w access to other files, e.g. under /sdcard/downloads/
So how can I add R/W permission for all files?
App below android 10
If you want to write and read any file in the External storage, you can use WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE
For Android 10
you can use requestLegacyExternalStorage=true in the application tag in your manifest. It will provide you the access to write file in External storage.
<application
android:name=".GlobalVars"
android:requestLegacyExternalStorage="true"
But it's a temporary solution. So the best solution is using SAF (Storage Access Framework) storage access framework or Scoped Storage Scoped storage
For android 11, Android system ignores the requestLegacyExternalStorage. So you can either Scoped storage or SAF to write any file into storage.
Also Note: If your app targets Android 11, it cannot access the files in any other app's data directory, even if the other app targets Android 8.1 (API level 27) or lower and has made the files in its data directory world-readable.
MANAGE_EXTERNAL_STORAGE is for Andoid 11+ devices.
For an Android 10 device add requestLegacyExternalStorage to manifest file.
I found the solution after some more research:
I ended up doing this:
Add this to manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<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_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" /> <!-- <uses-permission android:name="android.permission.WRITE_SETTINGS" /> -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Define the required permission to ask for:
public static List<Permissions> AppPermissions = Arrays.asList(
new Permissions("MANAGE_EXTERNAL_STORAGE", Manifest.permission.MANAGE_EXTERNAL_STORAGE),
new Permissions("READ_EXTERNAL_STORAGE", Manifest.permission.READ_EXTERNAL_STORAGE),
new Permissions("WRITE_EXTERNAL_STORAGE", Manifest.permission.WRITE_EXTERNAL_STORAGE),
new Permissions("READ_SMS", Manifest.permission.READ_SMS),
new Permissions("SEND_SMS", Manifest.permission.SEND_SMS),
new Permissions("ACCESS_BACKGROUND_LOCATION", Manifest.permission.ACCESS_BACKGROUND_LOCATION),
new Permissions("CAMERA", Manifest.permission.CAMERA),
new Permissions("RECORD_AUDIO", Manifest.permission.RECORD_AUDIO),
new Permissions("WRITE_CONTACTS", Manifest.permission.WRITE_CONTACTS),
new Permissions("READ_CONTACTS", Manifest.permission.READ_CONTACTS),
new Permissions("RECORD_AUDIO", Manifest.permission.READ_CALL_LOG)
);
Require those permission in mainActivity:
ActivityResultLauncher<String[]> mPermissionResultLauncher;
#Override
protected void onStart() {
mPermissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
#Override
public void onActivityResult(Map<String, Boolean> result) {
for(Permissions permission: GlobalVars.AppPermissions){
if (result.get(permission.ManifestName) != null) {
permission.IsGranted = result.get(permission.ManifestName);
}
}
}
});
if(Build.VERSION.SDK_INT >= 30) {
if (Environment.isExternalStorageManager()){
}else{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
requestPermission();
super.onStart();
}
private void requestPermission() {
// A simple check of whether runtime permissions need to be managed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> permissionRequest = new ArrayList<String>();
for(Permissions permission: GlobalVars.AppPermissions){
int pp = ContextCompat.checkSelfPermission(MainActivity.this, permission.ManifestName);
int pg = PackageManager.PERMISSION_GRANTED;
if (ContextCompat.checkSelfPermission(MainActivity.this, permission.ManifestName) != PackageManager.PERMISSION_GRANTED) {
permissionRequest.add(permission.ManifestName);
}
}
if (!permissionRequest.isEmpty()){
mPermissionResultLauncher.launch(permissionRequest.toArray(new String[0]));
}
}
}
I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.
I'm trying to use usb camera devices connected to my android device. So initially i have got the details of the usb devices connected through UsbManager.getDeviceList() method. Then i iterated through every device and requested for permission if permission was already not granted.
Prior to requesting the permission i have registered a global BroadCastReceiver to listen to the response of the requested permission.
Here is the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private UsbManager usbManager_;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
public PendingIntent permissionIntent;
private static String TAG = "testing";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SurroundView surroundView = new SurroundView(this);
// setContentView(surroundView);
usbManager_ = (UsbManager) getSystemService(USB_SERVICE);
permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
requestUsbPermissions();
}
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "received intent by broadcast " + intent.getAction());
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
Log.i(TAG, "got the permission");
}
} else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
public void requestUsbPermissions(){
HashMap<String, UsbDevice> deviceList = usbManager_.getDeviceList();
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
this.registerReceiver(usbReceiver, filter);
Log.i(TAG, "registered broadcast receiver!");
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
Log.i(TAG,
"Camera: device Id " + device.getDeviceId() + " device mName : " + device.getDeviceName());
if (!usbManager_.hasPermission(device)) {
Log.i(TAG, "requesting permission");
usbManager_.requestPermission(device, permissionIntent);
}
}
}
}
So when i run the app it detects one usb device connected and requests permission for the same. But the dialog box which asks for user input never comes. Instead when the intent is received by the BroadCastReceiver the value of intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) will always be false which means the permission is already denied. Can anyone explain to me why the dialog box is not coming in the first place and why the permission is denied automatically.
Here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vision_sdk_testing">
<uses-feature android:name="android.hardware.usb.host" android:required="true"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</manifest>
And below is the output log:
2020-05-01 17:56:05.282 30769-30769/com.example.vision_sdk_testing I/testing: registered broadcast receiver!
2020-05-01 17:56:05.283 30769-30769/com.example.vision_sdk_testing I/testing: Camera: device Id 1003 device mName : /dev/bus/usb/001/003
2020-05-01 17:56:05.283 30769-30769/com.example.vision_sdk_testing I/testing: requesting permission
2020-05-01 17:56:05.301 30769-30769/com.example.vision_sdk_testing I/testing: received intent by broadcast com.android.example.USB_PERMISSION
2020-05-01 17:56:05.302 30769-30769/com.example.vision_sdk_testing D/testing: permission denied for device UsbDevice[mName=/dev/bus/usb/001/003,mVendorId=1443,mProductId=38192,mClass=239,mSubclass=2,mProtocol=1,mManufacturerName=Sonix Technology Co., Ltd.,mProductName=USB 2.0 Camera,mVersion=1.00,mSerialNumberReader=android.hardware.usb.IUsbSerialReader$Stub$Proxy#d41ebfa,mConfigurations=[
UsbConfiguration[mId=1,mName=null,mAttributes=128,mMaxPower=128,mInterfaces=[
UsbInterface[mId=0,mAlternateSetting=0,mName=HD USB Camera,mClass=14,mSubclass=1,mProtocol=0,mEndpoints=[]]
UsbConfiguration[mId=3,mName=null,mAttributes=3,mMaxPower=88,mInterfaces=[]]
Any help is appreciated. Thanks!
For me, I had to go into the app's permissions in the settings menu and give my app the Camera permission. I'm guessing it's because my USB device is a camera? Once I granted this permission, the app worked just as described in the docs https://developer.android.com/guide/topics/connectivity/usb/host
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.
I need to connect to new wifi network programaticly to my device with this code:
`
try
{
String ssid = "\"" + SSID + "\"";
String pass = "\"" + Pass + "\"";
for (ScanResult result : results)
{
if (result.SSID.equals(SSID))
{
String security = getScanResultSecurity(result);
if (security.equals("PSK")) {
WifiConfiguration con = new WifiConfiguration();
con.SSID = ssid;
AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
a.setMessage("in");
a.show();
con.preSharedKey = pass;
con.hiddenSSID = true;
con.status = WifiConfiguration.Status.ENABLED;
con.allowedGroupCiphers.set(WifiConfiguration.Grou pCipher.TKIP);
con.allowedGroupCiphers.set(WifiConfiguration.Grou pCipher.CCMP);
con.allowedKeyManagement.set(WifiConfiguration.Key Mgmt.WPA_PSK);
con.allowedPairwiseCiphers.set(WifiConfiguration.P airwiseCipher.TKIP);
con.allowedPairwiseCiphers.set(WifiConfiguration.P airwiseCipher.CCMP);
con.allowedKeyManagement.set(WifiConfiguration.Key Mgmt.NONE);
con.allowedProtocols.set(WifiConfiguration.Protoco l.RSN);
con.allowedProtocols.set(WifiConfiguration.Protoco l.WPA);
int ntid = wifimanager.addNetwork(con);
wifimanager.disconnect();
wifimanager.enableNetwork(ntid,true);
wifimanager.reconnect();
boolean b = wifimanager.saveConfiguration();
if (ntid != -1 && b) {
AlertDialog a2 = new AlertDialog.Builder(MainActivity.this).create();
a2.setMessage("saved");
a2.show();
}
}
}
}
catch (Exception ex) {
AlertDialog a = new AlertDialog.Builder(MainActivity.this).create();
a.setMessage(ex.getMessage());
a.show();
}
`
but i can't add network to my device
problem is with network configuration that can't add to networks
I cant understand why doesn't work haven't erorr but no result
help me please
You should add permissions into manifest (and runtime permissions)
<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_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />