Requesting Runtime Permissions Causes Crash - java

The main reason I'm posting here is that I'm currently stuck without a computer that can run an emulator, I've been having to send the APK to my phone to test it. Even if my phone's connected to my computer, or I have a third party emulator running, it wont work. Due to this...I have no error logs.
The app is a simple password manager, and all the other functions thus far work. I was trying to add an export function, I can't get either to actually write anything. I've checked other questions and various sources online, but I cannot seem to figure out what could be causing it. When the method is called, it simply doesn't do anything as far as I can tell. I apologize if I'm missing something, or if there was indeed another question with the same issue. I couldn't find anything missing.
Here is the method I'm using;
EDIT: The code has been updated to reflect a better method of requesting runtime permissions, which was suggested here. This ultimately is what fixed the application.
//Method017: Exports the account info to a .txt file.
public void exportData() throws IOException {
//Opens dialog to request permission.
ActivityCompat.requestPermissions(Main.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
//Method to handle result of permission request.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Attempt to write a file to the Download folder.
String content = "hello world";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache");
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
//According to an online source, this is necessary to make the file viewable on the device.
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(Main.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
And my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.brand.psync">
<application
android:allowBackup="true"
android:icon="#drawable/psynclogo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:screenOrientation="portrait">
<activity android:name=".Main">
<intent-filter>
<action
android:name="android.intent.action.MAIN"
android:screenOrientation="portrait" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<category
android:name="android.intent.category.LAUNCHER"
android:screenOrientation="portrait" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Sorry about the lack of error log...but if I had that, I likely wouldn't need to post here.

I have try your code and it working.
public class SaveFileSampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lblBackground = new TextView(this);
lblBackground.setBackgroundColor(Color.WHITE);
setContentView(lblBackground);
ActivityCompat.requestPermissions(SaveFileSampleActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Attempt to write a file to the Download folder.
String content = "hello world";
File file;
FileOutputStream outputStream;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache");
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.close();
//According to an online source, this is necessary to make the file viewable on the device.
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(SaveFileSampleActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
And mainifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SaveFileSampleActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
It's work and result:
You can review your code. I hope it can help you!

Related

Phone not making calls with Intent Android_Call

I'm having some trouble with Intent Action_Call. I put the permission in Manifest, but it doesn't work. I press the button to Call and nothing happens. The app that I'm making is an app that does multiple Intents so the code isn't in MainActivity. I don't know if it helps, but I'm using API 28.
Thanks for reading.
MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentsimplicitas">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<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=".SmsActivity"></activity>
<activity android:name=".DialActivity" />
<activity android:name=".WaysActivity" />
<activity android:name=".MapActivity" />
<activity android:name=".PageActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
JAVA (DialActivity.java)
public class DialActivity extends Activity {
Button btnDial;
EditText edtPhone;
String phone;
Intent it;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dial);
btnDial = (Button)findViewById(R.id.btnDial);
edtPhone = (EditText)findViewById(R.id.edtPhone);
}
public void dialClick (View v) {
phone = edtPhone.getText().toString();
Uri uri = Uri.parse("tel: " + phone);
it = new Intent(Intent.ACTION_CALL);
it.setData(uri);
startActivity(it);
}
}
From https://developer.android.com/training/permissions/requesting:
Requesting permission:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.CALL_PHONE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.CALL_PHONE},
MY_PERMISSIONS_REQUEST_CALL_PHONE);
// MY_PERMISSIONS_REQUEST_CALL_PHONE is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
Verifying:
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
You can do via Intent
public void dialClick (View v) {
phone = edtPhone.getText().toString();
Uri uri = Uri.parse("tel: " + phone);
it = new Intent(Intent.ACTION_DIAL);
it.setData(uri);
startActivity(it);
}
You need to add the permissions at run time to be able to make the call, I recommend the following library, since it is much easier to implement the permissions in time of execution.
https://github.com/Karumi/Dexter

Install apk in android device from java code

I am trying to make a simple application in Java to install an APK on Android devices connected via USB. Using ABD manually or installing from Android Studio it works fine, but I wanted to give a simple single button click install option within my application, I have tried following code but unfortunately, it is not working
abdsourcesync = apkpath;
progress.setString("sync in progress");
System.out.println("Starting Sync via adb with command " + "adb"
+ " install -r " + apkpath);
Process process = Runtime.getRuntime().exec(
"adb" + " install -r " + apkpath);
InputStreamReader reader = new InputStreamReader(
process.getInputStream());
Scanner scanner = new Scanner(reader);
scanner.close();
int exitCode = process.waitFor();
System.out.println("Process returned: " + exitCode);
I have searched around here but I have only found installing an APK from within an Android application or from the android studio, not from a core Java. or java web module
Your helping hand would be really appreciated ;
Do not forget about runtime permissions
This simple example works for me for API 28.
It opens an apk file to install from "Download folder"
For simplification:
Download the apk file for application you want to install to "Download" folder of your phone. (There are a lot of instructions to do it programmaticaly, ot you can do it manualy)
TO DO
Create new project
Add a button to MainActivity
Create xml folder in res folder and create a file_paths.xml file there
Use the code bellow
Enjoy =)
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.teko.testcleanopenfile">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<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="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
MainActivity
public class MainActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView and button
textView = findViewById(R.id.textView);textView.setText("Hello updatable World\n");
(findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {RunAPK(getBaseContext());}
});
}
private void RunAPK(Context context){
requestPermissionsToRead();
}
private void requestPermissionsToRead() {
// ASK RUNTIME PERMISSIONS
ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE},111);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0) {
if (requestCode == 111 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
textView.append("Permission granted write\n");
// Create Uri
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file1 = new File (downloads + "//app-debug.apk");//downloads.listFiles()[0];
Uri contentUri1 = getUriForFile(this, BuildConfig.APPLICATION_ID, file1);
// Intent to open apk
Intent intent = new Intent(Intent.ACTION_VIEW, contentUri1);
intent.setDataAndType(contentUri1, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
}
}
}
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="download" path="."/>
</paths>
You can Install Application from Java code using below way.
File outputFile = null;
try {
outputFile = new File(<APK Path>);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", outputFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mContext.startActivity(intent);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
Uri apkUri = Uri.fromFile(outputFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}else {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}

Writing to external storage?

I have written codes from the tutorials of SLIDENERD to save info in different areas as internal cache,External cache,Private information and public information with the following codes.
EditText uname,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.editText);
pwd=(EditText)findViewById(R.id.editText3);
}
public void intCache(View view){
File fileDir=getCacheDir();
File myFile=new File(fileDir,"User_info_intCache.txt");
write(myFile);
}
public void extCache(View view){
File fileDir=getExternalCacheDir();
File myFile=new File(fileDir,"User_info_extCache.txt");
write(myFile);
}
public void pvtDir(View view){
File fileDir=getExternalFilesDir("User_Info");
File myFile=new File(fileDir,"User_info_pvtExt.txt");
write(myFile);
}
public void pubDir(View view){
File fileDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile=new File(fileDir,"User_info_pubExt.txt");
write(myFile);
}
private void write(File myFile){
String unameS=uname.getText().toString();
String pwdS=pwd.getText().toString();
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(myFile);
try {
fileOutputStream.write(unameS.getBytes());
fileOutputStream.write(pwdS.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
Toast.makeText(this,"data is written to "+myFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can see the files user_info_extCache.txt , User_info_pvtExt.txt. I know that internal cache location ( User_info_intCache.txt ) cant be seen.But i can't find the User_info_pubExt.txt file which must be stored in public directory Downloads.I cant see the file created by following code.
File fileDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile=new File(fileDir,"User_info_pubExt.txt");
The toast shows that the file is created by above piece of code under /storage/emulated/0/Download/User_info_pubExt.txt .
I find somewhere that if phone is connected to pc,external storage cant be accessed.So i tried both by removing the mobile from pc.The toast says that file is created.But i cant find it under that folder.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.iamka.storage">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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>
<activity android:name=".Main2Activity"></activity>
</application>
Your toast claiming that data is written is on the wrong place. As the toast also displays when there is an exception.
Place the toast in the try block instead. Or yet better after the close() but only if you close().
And place other toasts in the catch blocks to inform the user with e.getMessage().
As for the exception: all the paths exept the last one do not need any read/write permission at all. For the latter you need read/write permission.
But requesting them in manifest is not enough for Android 6+ as then you have to add some code to ask the user to confirm the requested permissions.
Google for runtime permissions.

Need help writing file to external storage

I've been searching the internet for several hours now in an attempt to find a file writing function that actually works for me. So far I have this in my MainActivity.java:
public void writeToFile(String data, Context ctx) {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File tempFile = new File(path, "houseDataFile.txt");
if(!tempFile.exists()){
tempFile.mkdirs();
}
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(ctx, "Saved", Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}
}
My android manifest contains both permissions:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="my.package.application"xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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">
</activity>
<activity android:name=".Menu_activity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Though rather frustratingly when I run the app and call writeToFile() it gives me an error saying:
W/MainActivity: FileOutputStream exception: - java.io.FileNotFoundException: /storage/emulated/0/Documents/houseDataFile.txt: open failed: ENOENT (No such file or directory)
Any help would be greatly appreciated, thank you in advance.
I'm assuming that you are failing to get the file path because you don't asking runtime-permission while executing method. Here you can take a look at the below code.
First, check if your device's OS version is above Lollipop or not. If above then show permission pop-up dialog.
final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1)
{
if (!checkIfAlreadyhavePermission())
{
ActivityCompat.requestPermissions(ProfileActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else
{
writeToFile(data, ctx);
}
}
else
{
writeToFile(data, ctx)
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
Then define "Allow" and "Deny" button functionalities in OnRequestPerMissionResult().
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
writeToFile( data, ctx);
} else {
Toast.makeText(YourActivity.this, "Please provide permission", Toast.LENGTH_LONG).show();
}
break;
}
}
Please let me know if this solves the issue.

Why listOfFiles is null?

Android says, that listOfFiles if null, so what have i done wrong?
I've tried to change getPath to getAboletePath, but it is just the same.
And, i've tried to access /storage/ (whereas SD_PATH is /storage/emulated/0) and i've got a list of 2 folders: emulated and self, both of wich are unaccessible.
public class MainActivity extends AppCompatActivity {
private static final String SD_PATH = Environment.getExternalStorageDirectory().getPath();
...
File home = new File(SD_PATH);
File[] listOfFiles = home.listFiles();
if(listOfFiles != null && listOfFiles.length > 0){
for (File file : home.listFiles()){
songs.add(file.getName());
}
}
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unimusic">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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>
</manifest>
This same thing has burned me in the past.
To quote the docs
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
(see here)
Reading from the file system is one of the permissions that must now be requested at run time in order to use. This is only an issue if you target SDK 23 or later. So how to fix:
The docs show an example (see here for the original) that I have modified for your use case (I have not run this code, but it should be a good starting point). You probably want to request permissions in the onCreate() for the Activity that is going to need the permission (in your case the MainActivity).
// Ask for the read external storage permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// Display a SnackBar with a button to request the missing permission.
Snackbar.make(layout,
"External storage is needed in order to {YOUR EXPLANATION HERE}",
Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// Request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}).show();
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}

Categories

Resources