Why my button work juste one time ? - Android studio - java

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();
}

Related

Send location via sms Button doesn't work - android studio

I tried to send my location via SMS, but the button doesn't work.
The button was working fine before I added the code of getting current location.
Can you please help me to fix that? I tried many solutions that I found in this website, but it doesn't work with me.
I am totally new to Android Studio, so I don't know how to write my code that it will work the way I want it.
private LocationManager locationManager;
private LocationListener locationListener;
String[] appPermissions = {
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.SEND_SMS
};
private static final int PERMISSIONS_REQUEST_CODE = 123;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
double x,y;
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkAndRequestPermissons()) {
}
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
x = location.getAltitude() ;
y = location.getLongitude();
Log.d("Location", location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
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("+212xxxxx", null, "Je suis en danger, voici ma localisation : https://www.google.com/maps/search/?api=1&query=" + x + "," + y , 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;
}
}
}
}
private boolean checkAndRequestPermissons() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions)
{
if (ContextCompat.checkSelfPermission(this,perm) != PackageManager.PERMISSION_GRANTED)
{
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray(
new String[listPermissionsNeeded.size()]),PERMISSIONS_REQUEST_CODE
);
return false;
}
return true;
}

BLUETOOTH_CONNECT permission

I have a problem, I try to activate Bluetooth but first I check for BLUETOOTH_CONNECT runtime permission (required by the BluetoothAdapter.enable()). Every time I request the permission is denied without displaying any dialog box, I tryed to request another permission and it works fine (displays dialog box with options - allow or denie) . I tryed to reinstall the app and clear its cache memory, i also checked for the app permissions allowed but i couldnt find Bluetooth. I also have the permissions in the Manifest.
public void enableordisableBT() {
if (MyBluetoothAdapter == null) {
Log.d(TAG,"Bluetooth not supported");
} else if (!MyBluetoothAdapter.isEnabled()) {
Log.d(TAG,"Bluetooth is currently not enabled");
if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "You have already granted this permission!", Toast.LENGTH_SHORT).show();
MyBluetoothAdapter.enable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
else
{
requestConnectPermission();
}
} else if (MyBluetoothAdapter.isEnabled()) {
MyBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
private void requestConnectPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH_CONNECT)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed because of this and that")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT}, CONNECTION_REQUEST_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, CONNECTION_REQUEST_CODE);
Log.d(TAG," permisiune in curs de cerere ");
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CONNECTION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Permission Granted,access to connection available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied, access to connection unavailable, app requires BLUETOOTH_CONNECT permission in order to operate", Toast.LENGTH_LONG).show();
}
break;
case SCAN_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Permission Granted,access to scan available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied, access to scan unavailable, app requires BLUETOOTH_SCAN permission in order to operate", Toast.LENGTH_LONG).show();
}
break;
}
}

How Do I send A Text Via SmsManager?

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;
}
}
}
}

onResult() callback from ResultCallback<LocationSettingsResult> is never called

I am trying to check the user's Location settings before retrieving their location but I cannot get the onResult callback to fire. I first initialized the GoogleClientApi object in onCreate() and tried debugging, it says "No such instance field" at the result.setResultCallback() breakpoint. I have spent numerous hours on this, please help me out!
public class MainActivity extendsAppCompatActivity
implements,OnConnectionFailedListener{
private static final int PERMISSION_CODE = 23;
private static final int RESOLUTION_CODE = 0x1;
public GoogleApiClient googleClient;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
checkLocationSettings();
}
public void checkLocationSettings() {
googleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addOnConnectionFailedListener(this)
.build();
LocationSettingsRequest.Builder locationSettingsBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(new LocationRequest().setInterval(5000)).setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleClient
, locationSettingsBuilder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
checkLocationPermission();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MainActivity.this, RESOLUTION_CODE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(MainActivity.this, "Location is missing", Toast.LENGTH_LONG).show();
}
}
});
}
private void checkLocationPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
} else {
googleClient.connect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESOLUTION_CODE:
switch (resultCode) {
case RESULT_OK:
checkLocationPermission();
break;
case RESULT_CANCELED:
Toast.makeText(MainActivity.this, "Location is required, turn it on", Toast.LENGTH_SHORT).show();
break;
}
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
googleClient.connect();
} else {
Toast.makeText(MainActivity.this, "Error Activty", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleClient);
textView.setText(location.getLatitude() + location.getLongitude() + "");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onStop() {
super.onStop();
if(googleClient.isConnected()){
googleClient.disconnect();
}
}
}
From these SO threads, No such instance field and Initialize boolean value "no such instance field", if there wasn't a problem with the code, try restarting Android Studio. Maybe it's using an incorrect file from the previous version. This thread: Why is LocationSettingsResult startResolutionForResult not calling onActivityResult? might also help on how to connect to GoogleApiClient for getting the user's location.

Displaying a TextView depending on whether Android permission is disabled?

I'm trying to display a TextView which appears visible only when a particular Android permission, i.e. WRITE_EXTERNAL_STORAGE, is not enabled. The idea is to explain to the user why they need to enable it in case they've disabled it the first time, and then have them click the TextView to launch the permission request again. The following is not working for me. How can I accomplish this? I have this in my onCreate() method:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
if (NetworkHelper.isOnline(this)) {
new AppendParseData().execute();
}
}
TextView checkFilePermission = (TextView) findViewById(R.id.checkFilePermission);
if (!checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
checkFilePermission.setVisibility(View.VISIBLE);
}
try this way when you request for permission(I have used READ_CONTACTS permission you can use WRITE_EXTERNAL_STORAGE instead)
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
requestContactsPermissions1();
} else {
setTextVisablity(false);
checkSimCard();
}
in onRequestPermissionsResult
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
readContacts();
setTextVisablity(false);
} else {
// Permission Denied
setTextVisablity(true);
Toast.makeText(MainActivity.this, "READ_CONTACTS Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
in the end setTextVisablity method
public void setTextVisablity(boolean isShow) {
if (isShow) {
tv.setVisibility(View.VISIBLE);
} else {
tv.setVisibility(View.GONE);
}
}
Use this code:-
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
return;
}
else{
//Permission already granted show textview here
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
Toast.makeText(MainActivity.this, " PERMISSION_GRANTED", Toast.LENGTH_SHORT)
.show();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, " Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Categories

Resources