I'm Working with the action call in the android - java

I've done the code for placing the call and the thing is i want to place the call from the number which i stored in the database means i want dynamic calling action in my app...
Hoe do i do that....Any Help would be appreciated......
THANKS IN ADVANCE!!!!!
My code for placing the callsss......is right under below....
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9855956530"));
startActivity(callIntent);
if (Build.VERSION.SDK_INT >= 23) {
if (getActivity().checkSelfPermission(android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 1);
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
}
}
});
And i used the fragments in this app
Database is Sqlite Database

Related

No Activity found to handle Intent when trying to programmatically ask for permissions

I need to get the MANAGE_ALL_FILES_ACCESS_PERMISSION to be able to download and install APK's from my application.
When I was targeting SDK 27 and lower, everything worked fine, when I declared
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and asked for permission with ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
But now I need to target SDK 30, meaning that WRITE_EXTERNAL_STORAGE is deprecated and not working for API versions 29 and 30.
I have been trying to find a workaround and one that I could think of was starting the Intent to allow users to switch the permission on by themselves but I cannot get it to work.
The code I am using:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
Uri uri = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri);
startActivity(intent);
} catch (Exception ex){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);
}
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
And the error that I get when trying to open intent:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.MANAGE_ALL_FILES_ACCESS_PERMISSION }
The error comes from the catch block but the Exception ex gives the same error.
What am I doing wrong or is this just not allowed on the current phone I am using (XCover 4s Android 10).
The answer to getting the storage permission that worked for me.
I had to change the Manifest.permission. strings so instead of what was written in the question I used.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ActivityCompat.requestPermissions(
activity,
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE
},
1
);
} else {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
Or similarly this could be used :
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
Then to get the prompt to allow user to install Apps from unkown sources :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!activity.getPackageManager().canRequestPackageInstalls()) {
activity.startActivityForResult(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName()))), 1234);
} else {
}
}
I had this problem when I was trying to navigate the user to enable all files access permission on the app screen directly.
Solution for this one is to add the package name like this:
val storageIntent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:$packageName"))

Data Retrieval from Firestore is erratic

I'm working on an Android app that does the following:
Upon app start-up, it checks if a user is logged in, using AuthStateListener.
If there is a user logged in, it retrieves data from Firestore. The user data is stored in a document that I named with the following nomenclature: "User " + user's_email_ID. For example, if a user has an email ID xyz#gmail.com, his data will be stored in the document named: User xyz#gmail.com.
All documents are within the collection named "Users".
If all the fields are null/ empty in the user's data document, the app opens an Activity that asks him/her to fill all the details. Else, it takes the user to the main page (StudentMainActivity if the user is a student, or ProfessorMainActivity if the user is a professor).
Coming to my problem:
The block of code which checks whether the fields are empty has some erratic and unpredictable behavior. I'm not sure if this is a problem based on Firestore, or on the fact that data retrieval happens on a different thread.
I checked the Firestore database and saw that all fields were filled. However, when a user (who's already logged in) starts the app, the app knows that it is the same user (i.e. he's not prompted to sign in, because AuthStateListener does its job), but instead of being redirected to either StudentMainActivity or ProfessorMainActivity (the main screens), he's asked to fill his details again.
What's more confusing is that this bug doesn't always occur. There are times when the app does what is expected, i.e. take the user to the main screen, but the next time he starts the app, he's again taken to the activity that asks him to enter his details.
Source Code:
LoginActivity.java (Only the relevant parts)
//AuthStateListener is in onCreate
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
UIDEmailID = user.getEmail();
updateUI(user);
}
else{
updateUI(null);
}
}
};
private void updateUI(FirebaseUser user){
// Update UI after login
if (user != null) {
Toast.makeText(LoginActivity.this, "User " + UIDEmailID, Toast.LENGTH_LONG).show();
db.collection("Users").document("User " + UIDEmailID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.get("department") != null || // if any
documentSnapshot.get("phoneNumber") != null || // field in
documentSnapshot.get("name") != null || // Firestore is
documentSnapshot.get("studentSemester") != null || // non-null then
documentSnapshot.get("dateOfBirth") != null || // proceed to
documentSnapshot.get("university") != null) { // further activities
if (documentSnapshot.get("userType") == "Lecturer/ Professor") {
Intent intent = new Intent(LoginActivity.this, ProfessorMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
Intent intent = new Intent(LoginActivity.this, StudentMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} else {
Toast.makeText(LoginActivity.this, "We need some additional details before we go ahead.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, GFBDetailsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
I'm sorry for the long question; I just tried to make it super descriptive. Some help would be greatly appreciated.
P.S. The reason I think this is a problem involving the usage of multiple threads is because whenever the app runs as expected (i.e. takes the user to the main screen), the toast "We need some additional details before we go ahead." appears as well. If you look at the code (the last "else" block) you will realise that it is in a seperate conditional block altogether, and thus isn't even supposed to show up if the main screen (which is in another conditional block) shows up.
EDIT 1:
I'm enclosing screenshots pertaining to the problem. Ignore the bland UI :P
This is what's expected (Comes under the second 'else' block). It is supposed to show up only if the user is logging in for the first time, i.e. does not have his data stored in a Firestore document.
The background is StudentMainActivity (inside the nested 'else'). However, even the Toast is displayed (it belongs to a seperate block altogether).
So it turns out Firestore wasn't (entirely) at fault.
Every activity in an Android application has a life span, and every time an activity is run, it goes through an elaborate sequence of lifecycle functions.
An activity's lifecycle is as follows:
Launched --> onCreate() --> onStart() --> onResume() --> Running --> onPause() --> onStop() --> onDestroy() --> Finished
I won't be digressing by going into the details of each function, because the function names are quite intuitive and self-explanatory.
As you can see in the code snippet in the question, onAuthStateChanged() is inside onCreate(). My Document ID on Firebase is of the form "User UIDEmailID", where UIDEmailID is the email ID of the user. And UIDEmailID gets updated only in onAuthStateChanged() (which, in turn, is inside onCreate()), i.e. only when the activity starts afresh, after the app has been closed and opened again.
Therefore, I updated UIDEmailID in onStart() as well, which means that every time an app is resumed, it will retrieve the email ID of the user, which can subsequently be used to retrieve the document from Firestore.
Also, I slightly tweaked my Firestore data retrieval bit of code upon advice from Nibrass H. The solution is as follows:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
running = true;
if (savedInstanceState != null){
running = savedInstanceState.getBoolean("running");
wasrunning = savedInstanceState.getBoolean("wasrunning");
}
setContentView(R.layout.splash_screen);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth1) {
FirebaseUser user = firebaseAuth1.getCurrentUser();
if (user != null){
UIDEmailID = user.getEmail();
updateUI(user);
} else {
updateUI(null);
}
}
};
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
if (firebaseAuth.getCurrentUser() != null) {
UIDEmailID = firebaseAuth.getCurrentUser().getEmail();
updateUI(firebaseAuth.getCurrentUser());
} else {
updateUI(null);
}
}
#Override
protected void onRestart() {
super.onRestart();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth1) {
FirebaseUser user = firebaseAuth1.getCurrentUser();
if (user != null) {
UIDEmailID = user.getEmail();
updateUI(user);
} else {
updateUI(null);
}
}
};
}
#Override
protected void onPause() {
super.onPause();
wasrunning = running;
running = false;
}
#Override
protected void onResume() {
super.onResume();
if (wasrunning){
running = true;
}
}
#Override
protected void onStop() {
super.onStop();
if (authStateListener != null) {
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
private void updateUI(FirebaseUser firebaseUser){
if (firebaseUser != null){
Toast.makeText(this, "User " + firebaseUser.getEmail(), Toast.LENGTH_SHORT).show();
db.collection("Users").document("User " + UIDEmailID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.get("userType") != null) {
if (documentSnapshot.get("userType").equals("Lecturer/ Professor")){
Intent intent = new Intent(SplashScreenActivity.this, ProfessorMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
startActivity(intent);
} else {
Intent intent = new Intent(SplashScreenActivity.this, StudentMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
startActivity(intent);
}
} else {
Toast.makeText(SplashScreenActivity.this, "We need some additional details before we go ahead.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SplashScreenActivity.this, GFBDetailsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
startActivity(intent);
}
}
});
}
}

Check if an intent data is null or not?

I have a streaming app which plays video in ExoPlayer2. I added an intent which opens the video in the external player but I want to check if the getData() is empty/null and if so, then show a toast or proceed with the intent.
My code:
imgExternal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if(getIntent().getData() == null) {
new ToastMsg(DetailsActivity.this).toastIconError("Sorry but there was an error retrieving the url!");
} else {
intent.setData(Uri.parse(listDirector.get(0).getStremURL()));
startActivity(Intent.createChooser(intent, "Open In"));
}
}
});
Now the problem is, my app thinks everything is null and showing me toast so any help would be appreciated.
You can check
if (listDirector.get(0).getStremURL() == null) {
new ToastMsg(DetailsActivity.this).toastIconError("Sorry but there was an error retrieving the url!");
} else {
intent.setData(Uri.parse(listDirector.get(0).getStremURL()));
startActivity(Intent.createChooser(intent, "Open In"));
}
Instead of getIntent().getData() try using this.getIntent().getData()

Unable to upload image first time, it works in the second time

I am uploading any type of file from my code but the problem is when I run my code for the first time and try to upload an image, the image not being uploaded in that time. If I upload a file first, e.g. a PDF file, it is being uploaded successfully and after that when I upload an image, it is uploaded successfully as well. I don't understand anything about the problem. Please help.
Here is the code for uploading an image/file.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
showFileChoser();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);
}
} else {
showFileChoser();
}
And the showFileChoser function.
private void showFileChoser() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select document"), PICK_DOCUMENT);
}
The onActivityResult.
// Handling the ima chooser activity result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
// uploadMultipart();
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And onRequestPermissionsResult is...
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
The file uploading function is the following.
private void execMultipartPost() throws Exception {
RequestBody requestBody;
pBar.setVisibility(View.VISIBLE);
final SessionManager session = new SessionManager(getActivity());
final HashMap<String, String> loggedDetail = session.getLoggedDetail();
HashMap<String, String> params = new HashMap<String, String>();
String api_token = loggedDetail.get("api_token");
if (filePath != null) {
String path = FilePath.getPath(getActivity(), filePath);
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("identity_file", path)
.addFormDataPart("training", edtTraining.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("experience", experience)
.addFormDataPart("skills", edtSkills.getText().toString())
.addFormDataPart("address_file", "")
.addFormDataPart("cv_file", "")
.addFormDataPart("dbs_file", "")
.build();
}
}
As far as I can assume, you are calling the requestPermissions function from a Fragment. As you are using ActivityCompat.requestPermissions for asking permission from the user, the onRequestPermissionsResult is not being invoked in the Fragment. Here is a similar problem which indicates the Fragment's onRequestPermissionsResult not being called and the calling Activity's onRequestPermissionsResult is being called instead. I assume this is what happens in your case as well.
Now to get rid of this problem, you need to use
requestPermissions(new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);
instead of
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, STORAGE_PERMISSION_CODE);
Do not use ActivityCompat.requestPermissions in your Fragment, as this will invoke the onRequestPermissionResult of your calling Activity which is launching the Fragment.
Hope that helps.

Button to end or finish voice call in my own App in Android Studio

I have made an application that makes the calls to a telephone number, but I also want it to have the "end call" button in this application. In case it can't, then it can have the option to force the application to stop calls
btn_llamadas.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse("tel:945192696")); //
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(i);
}
});
You would have to use a PhoneStateListener to check if the call is ended or now.
Check this link for instructions.

Categories