I have been trying to send test messages from using send_sms api. My SMSPortalFragment.java code show no error. Also there is no other error shown in Logcat.
The code builds and installs in the Galaxy S8.
The app runs fun.
Going to fragment_smsportal.xml is working fine.
I can type in my name and message.
On button click it asks for my PERMISSION in runtime.
NO MESSAGE IS SENT EVEN AFTER I ALLOW PERMISSION.
java code:
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendButon;
EditText fullName;
EditText textMessage;
String phoneNo = "***********";
String name;
String message;
String sendMessage;
public SMSPortalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View smsportal = inflater.inflate(R.layout.fragment_smsportal, container, false);
fullName = (EditText) smsportal.findViewById(R.id.fullName);
textMessage = (EditText) smsportal.findViewById(R.id.textMessage);
sendButon = (Button) smsportal.findViewById(R.id.sendButon);
sendButon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSMSMessage();
}
});
return smsportal;
}
private void sendSMSMessage() {
name = fullName.getText().toString();
message = textMessage.getText().toString();
sendMessage = name + " " + message;
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sendMessage, null, null);
Toast.makeText(getActivity(),"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(),"SMS failed, please try again.", Toast.LENGTH_LONG).show();
}
}
}
}
Can anyone tell me what I am doing wrong?
PS: I removed my phone number from this code for security concern.
Do not write your send logic in onRequestPermissionsResult()
and
Try this...
Manifest permission
<uses-permission-sdk-23 android:name="android.permission.SEND_SMS"/>
and here is the snippet
try {
Bundle msgDataBundle = intent.getExtras();
String mobileNumber = msgDataBundle.getString("MobileNumber");
SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage(mobileNumber,null,"sam",null,null);
smsManager.sendTextMessage(mobileNumber, null, "Test Sample Message Text", null, null);
Toast.makeText(context, "SMS Sent!", Toast.LENGTH_LONG).show();
Log.d("---", "Sent");
} catch (Exception e) {
Toast.makeText(context, "SMS faild, please try again.", Toast.LENGTH_LONG).show();
Log.d("---", "Fail");
e.printStackTrace();
}
Related
I am trying tp send sms by clicking a button bt this button is working juste one time.
And i don't know how I can get it so the button can be pressed an infinite amount of time.
Can you please help me to fix that.
this is my code :
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxxx", null, "Je suis en danger, voici ma localisation : https://goo.gl/maps/xamxKW62p34wWpBU8", null, null);
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
You are missing else branch in sendSMSMessage, so you are not sending SMS if SEND_SMS permission is already granted. You are also not doing anything if you need to show permission rationale, which results in a broken experience.
Overall I would suggest to read carefully the docs on requesting permissions. It explains both your approach with onRequestPermissionsResult as well as the new recommended way of using ActivityResultContracts.
Without rewriting your code to the contracts I would fix it like this:
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
// fixme: show explanation
// before requesting the permission again
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
} else {
sendSmsImpl();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendSmsImpl();
} else {
// fixme: explain that it can't send SMS without the permission
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
// !!! NOTE: you still need break inside switch/case
// even with curly braces
break;
}
}
}
private void sendSmsImpl() {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxxxxx", null, "Je suis en danger, voici ma localisation : https://goo.gl/maps/xamxKW62p34wWpBU8", null, null);
//todo: use sentIntent argument of sendTextMessage to detect success/error
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
}
My app
Hello, I have designed an application that receives messages and device information as shown in the image and show the TextView,
But now how to get messages and device information to an example api file.php in the host?
For example this is my php file in host:
http://example.com/api/file.php
How i Send it?!!
Please help to me i can complete the app
This is my MainActivity.java
codes:
setContentView(R.layout.main);
num = (TextView) findViewById(R.id.sender);
msg = (TextView) findViewById(R.id.content);
manufacturerTxt = findViewById(R.id.DeviceName);
modelTxt = findViewById(R.id.DeviceModel);
versionTxt = findViewById(R.id.AndroidVersion);
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
String version = Build.VERSION.RELEASE;
int sdk = Build.VERSION.SDK_INT;
String hardware = Build.HARDWARE;
manufacturerTxt.setText(manufacturer);
modelTxt.setText(model);
versionTxt.setText(version);
receiveFilter = new IntentFilter();
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
messageReceiver = new MessageReceiver();
registerReceiver(messageReceiver, receiveFilter);
to = (EditText) findViewById(R.id.to);
msgInput = (EditText) findViewById(R.id.msg_input);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED)
{
MessageSent();
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},100);
}
}
});
}
private void MessageSent() {
String num=to.getText().toString().trim();
String msg=msgInput.getText().toString().trim();
if(!num.equals("") && !msg.equals(""))
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null,msg, null, null);
Toast.makeText(getApplicationContext(),"sent",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"fill the fields",Toast.LENGTH_SHORT).show();
}
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(messageReceiver);
}
class MessageReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address = messages[0].getOriginatingAddress();
String fullMessage = "";
for (SmsMessage message : messages) {
fullMessage += message.getMessageBody();
}
num.setText(address);
msg.setText(fullMessage);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
MessageSent();
}
else {
Toast.makeText(getApplicationContext(),"permission denied",Toast.LENGTH_LONG).show();
}}
}
}
To use REST APIs, you should use a library called Retrofit or Volley.
You can check these two libraries and get an idea as to how to send messages over a HTTP REST API.
Reference:
Volley
Retrofit
I have included SHA1, and SHA-256 in firebase project.
while fragment is running an Exception Toast Message appears: "This request is missing a valid app indenitier, meaning that neither SafetyNet checks nor reCAPTCHA checks succeeded. Please try again, or checkc the logcat for more details".
Code:
public class VerifyPhoneFragment extends Fragment {
public static String source = null;
PinView pinView;
String phoneNo;
boolean verified = false;
private String VerificationCodSent;
private String CodeEnteredByUser;
public VerifyPhoneFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
final NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
final ProgressBar progressBar = view.findViewById(R.id.progress_bar);
ImageView backArrowImageView = view.findViewById(R.id.back_arrow);
TextView backTextView = view.findViewById(R.id.back_text_view);
TextView otpMobileTextView = view.findViewById(R.id.otp_mobile_tv);
Button verifyButton = view.findViewById(R.id.verify_button);
pinView = view.findViewById(R.id.pin_view);
if(source.equals("SignUpFragment")){
phoneNo = "+" + SignUpFragment.mobileTxt;
}
else if(source.equals("LoginFragment")){
phoneNo = "+" + LoginFragment.mobileTxt;
}
else if(source.equals("ForgotPasswordFragment")){
phoneNo = "+" + ForgotPasswordFragment.mobileTxt;
}
otpMobileTextView.setText("Enter OTP sent to Your Phone" + "\n" + phoneNo);
backArrowImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
navController.navigate(R.id.verifyPhone_to_login);
}
});
backTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
navController.navigate(R.id.verifyPhone_to_login);
}
});
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNo,
60,
TimeUnit.SECONDS,
getActivity(),
new PhoneAuthProvider.OnVerificationStateChangedCallbacks(){
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
VerificationCodSent = phoneAuthCredential.getSmsCode();
if(VerificationCodSent != null){
progressBar.setVisibility(View.VISIBLE);
verifyButton.setVisibility(view.INVISIBLE);
PhoneAuthCredential phoneAuthCredential1 = PhoneAuthProvider.getCredential(
VerificationCodSent,
CodeEnteredByUser
);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
verifyButton.setVisibility(View.VISIBLE);
if(task.isSuccessful()){
verified = true;
}
else{
Toast.makeText(getContext(), "the Verification Code entered was invalid", Toast.LENGTH_LONG).show();
verified = false;
}
}
});
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(#NonNull String VerificationCodeSent, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
VerificationCodSent = VerificationCodeSent;
}
}
);
verifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pinView.getText().toString().isEmpty()){
Toast.makeText(getContext(), "Please enter a valid verification code", Toast.LENGTH_LONG).show();
verified = false;
goToAppropriateFragment(source);
}
CodeEnteredByUser = pinView.getText().toString();
if(VerificationCodSent != null){
progressBar.setVisibility(View.VISIBLE);
verifyButton.setVisibility(view.INVISIBLE);
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(
VerificationCodSent,
CodeEnteredByUser
);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
verifyButton.setVisibility(View.VISIBLE);
if(task.isSuccessful()){
verified = true;
}
else{
Toast.makeText(getContext(), "the Verification Code entered was invalid", Toast.LENGTH_LONG).show();
verified = false;
}
}
});
}
// afterVerification
goToAppropriateFragment(source);
}
});
}
public void goToAppropriateFragment(String source){
final NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
if(source.equals("SignUpFragment")){
if(verified){
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
if(databaseHelper.addNewUser()){ // if the user added successfully addUser() returns true
Toast.makeText(getContext(), "You have signed up successfully! you can login", Toast.LENGTH_LONG).show();
// go to LoginFragment
navController.navigate(R.id.verifyPhone_to_login);
}
else{ // to be deleted won't arrive here if email is already used
Toast.makeText(getContext(), "Sorry, Unable to sign you up! Try again later", Toast.LENGTH_LONG).show();
}
}
else {
// Toast.makeText(getContext(), "Sorry, it seems that you have not entered the OTP correctly. Try again", Toast.LENGTH_LONG).show();
// go to SignUpFragment
navController.navigate(R.id.verifyPhone_to_signUp);
}
}
else if(source.equals("LoginFragment")){
if(verified){
// go to MainContentActivity
Toast.makeText(getContext(), "Welcome back " + LoginFragment.fNameTxt + "!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getContext(), MainContentActivity.class);
startActivity(intent);
}
else {
// Toast.makeText(getContext(), "Sorry, it seems that you have not entered the OTP correctly. Try again", Toast.LENGTH_LONG).show();
// go to LoginFragment
navController.navigate(R.id.verifyPhone_to_login);
}
}
else if(source.equals("ForgotPasswordFragment")){
if(verified){
// go to ResetPasswordFragment
navController.navigate(R.id.verifyPhone_to_resetPassword);
}
else {
Toast.makeText(getContext(), "Sorry, it seems that you have not entered the OTP correctly. Try again", Toast.LENGTH_LONG).show();
// go to LoginFragment
navController.navigate(R.id.verifyPhone_to_login);
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_verify_phone, container, false);
}
}
Logcat:
2021-03-30 20:57:21.769 16847-16847/com.example.map_project_v2 E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2021-03-30 20:57:50.049 16847-16847/com.example.map_project_v2 E/zzf: Problem retrieving SafetyNet Token: 7:
2021-03-30 20:57:51.267 16847-17116/com.example.map_project_v2 E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
2021-03-30 20:57:51.381 16847-16847/com.example.map_project_v2 E/zzf: Failed to get reCAPTCHA token with error [There was an error while trying to get your package certificate hash.]- calling backend without app verification
2021-03-30 20:57:51.763 16847-16976/com.example.map_project_v2 E/FirebaseAuth: [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17093 null
I was getting the same error and I could solved it with the last two steps of the following (make sure you have covered all of them):
Enable Phone option in Sign-in method under Firebase Authentication
Make sure to download and add the latest google-services.json file in your project
Enable Android Device Verification for your firebase project in https://console.cloud.google.com/
Add library implementation "androidx.browser:browser:1.3.0"
https://developer.android.com/jetpack...
so I have a button that when clicked, I want to send a text message. To who, is specified by the editText. When I use the app, it says that the text is sent, however when I check in my messaging app it shows that nothing sent. How do I remedy this?
Example Number: "8667404531" (This is a bot hotline for example)
EditText editText = (EditText) findViewById(R.id.editText);
String myNum = editText.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(myNum, null, "Wake Up!", null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
First, make sure you have set this permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.SEND_SMS"/>
Secondly, you should check self permission before you can send any messages. You can achieve that with checkSelfPermission() call and corresponding onRequestPermissionsResult() callback.
Check out this code below, it contains important parts related to requesting permissions from the device. This code below is a complete example of Activity for sending SMS from your device:
public class MainActivity extends AppCompatActivity {
EditText number, text;
Button send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = (EditText) findViewById(R.id.editText);
text = (EditText) findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS}, 1);
}
} else {
//do nothing
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = number.getText().toString();
String messageText = text.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, messageText, null, null);
Toast.makeText(MainActivity.this, "Message sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e){
Toast.makeText(MainActivity.this, "Sending failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case 1:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Permission granted!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Permission not granted!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
I am trying to increment a float number once the Phone State is IDLE. Then save the float number in shared preferences and expose it in the main activity.
Currently what i did was use intent to take in the number on phone state and send to the main activity and on the main activity i saved it. But the phone crashes once i test it. Below is my current code for the Incoming Call:
public class IncomingCall extends BroadcastReceiver {
private View view;
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
Intent intentBundle = new Intent();
Bundle bundle = new Bundle();
bundle.putFloat("value", 0.5f);
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
bundle.putFloat("value", 0.5f);
intentBundle.putExtras(bundle);
Toast toast = new Toast(context);
CharSequence text = "O.5 Added";
int duration = Toast.LENGTH_SHORT;
Toast testtoast = Toast.makeText(context, text, duration);
testtoast.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the code i have in my main activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private float minteger = 0.5f;
private Context context;
private Activity activity;
private static final int PERMISSION_REQUEST_CODE = 1;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.appname.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putFloat("value", minteger).apply();
Float value = sharedPreferences.getFloat("value", 0.0f);
TextView textv = (TextView) findViewById(R.id.numberValue);
textv.setText(String.valueOf(value));
context = getApplicationContext();
activity = this;
Button check_permission = (Button) findViewById(R.id.check_permission);
Button request_permission = (Button) findViewById(R.id.request_permission);
check_permission.setOnClickListener(this);
request_permission.setOnClickListener(this);
}
#Override
public void onClick(View v) {
view = v;
int id = v.getId();
switch (id) {
case R.id.check_permission:
if (checkPermission()) {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Please request permission.", Snackbar.LENGTH_LONG).show();
}
break;
case R.id.request_permission:
if (!checkPermission()) {
requestPermission();
} else {
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_PHONE_STATE)) {
Toast.makeText(context, "Phone state allows you to earn on incoming calls. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view, "Permission Granted, Now you can access phone manager.", Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view, "Permission Denied, You cannot access phone manager.", Snackbar.LENGTH_LONG).show();
}
break;
}
}
}
You could put the value to sharedpref in IncomingCall and retrieve in MainActivity.