I'm having a problem with my application. The application is supposed to send a message using volume key buttons on the phone. The problem is that it keeps stopping and I do not know if it works. Here is the code, I also added some wake lock in order for my app to stay active even when phone is locked.
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
sendMessage.setEnabled(true);
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
sendMessage.setEnabled(true);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
Right now your code is not sending any messages when you press the volume key nor when you release it. You need to add this to your code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
...
}
Also, you're missing n opening bracket on the final else of your onKeyDown()
Related
I want to send an SMS with location to the contact that the user has been saved. But I don't know how to do it. 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.
Please, can you help me to do that?
This is the code of sending SMS:
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)) {
// 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("+212xxx", null, "Je suis en danger, voici ma localisation : https://www.google.com/maps/search/?api=1&query=<lat>,<lng>", null, null);
//todo: use sentIntent argument of sendTextMessage to detect success/error
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
}
And this the code of saving contact:
private int id;
private String phoneNo;
private String name;
// constructor
public ContactModel(int id, String name, String phoneNo) {
this.id = id;
this.phoneNo = validate(phoneNo);
this.name = name;
}
// validate the phone number, and reformat is necessary
private String validate(String phone) {
// creating StringBuilder for both the cases
StringBuilder case1 = new StringBuilder("+212");
StringBuilder case2 = new StringBuilder("");
// check if the string already has a "+"
if (phone.charAt(0) != '+') {
for (int i = 0; i < phone.length(); i++) {
// remove any spaces or "-"
if (phone.charAt(i) != '-' && phone.charAt(i) != ' ') {
case1.append(phone.charAt(i));
}
}
return case1.toString();
} else {
for (int i = 0; i < phone.length(); i++) {
// remove any spaces or "-"
if (phone.charAt(i) != '-' || phone.charAt(i) != ' ') {
case2.append(phone.charAt(i));
}
}
return case2.toString();
}
}
public String getPhoneNo() {
return phoneNo;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am working on a project for school and trying to send SMS to the user phone. The message is sent twice instead of once. How do I fix that problem?
Here is my code:
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =1 ;
EditText textphone;
String message;
String phoneNo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_e_g_i_s_t_e_r);
textphone=findViewById(R.id.phone);
c = findViewById(R.id.create1);
c.setOnClickListener(this);
c.setEnabled(false);
if(!checkPermission(Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}else{
c.setEnabled(true);
}
}
public void onClick(View v) {
if (v == c) {
sendmessage();}
now the method:
private void sendmessage() {
if(checkPermission(Manifest.permission.SEND_SMS))
{
message="Hello "+ username2.getText().toString()+",welcome to Chatime. Hope you enjoy from our app.";
phoneNo=textphone.getText().toString();
if(phoneNo.length()==0){
return;
}
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message,null,null);
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
public boolean checkPermission(String permission){
int check=ContextCompat.checkSelfPermission(this,permission);
return (check==PackageManager.PERMISSION_GRANTED);
}
in my code the permission log will be display but the phone number is not visible in toast
how to get simcard number in the toast message with the use of explicit permission
public class MainActivity extends AppCompatActivity {
String TAG = "PhoneActivityTAG";
Activity activity = MainActivity.this;
String wantPermission = Manifest.permission.READ_PHONE_STATE;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkPermission(wantPermission)) {
requestPermission(wantPermission);
} else {
Log.d(TAG, "Phone number: " + getPhone());
}
}
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
}
return phoneMgr.getLine1Number();
}
private void requestPermission(String permission){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
Toast.makeText(activity, "Phone state permission allows us to get phone number. Please allow it for additional functionality.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(activity, new String[]{permission},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) {
Log.d(TAG, "Phone number: " + getPhone());
} else {
Toast.makeText(activity,"Permission Denied. We can't get phone number.", Toast.LENGTH_LONG).show();
}
break;
}
}
private boolean checkPermission(String permission){
if (Build.VERSION.SDK_INT >= 23) {
int result = ContextCompat.checkSelfPermission(activity, permission);
return result == PackageManager.PERMISSION_GRANTED;
} else {
return true;
}
}
}
please help me
how can i get phone number in the display toast?
checkout the answer written here.
some correction in code
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
}
return phoneMgr.getLine1Number();
}
I have create program which can send message. when I use Activity.checkSelfPermission, it show the error like "The method checkSelfPermission(MainActivity, String) is undefined for the type ActivityCompat". I have import android.support.v4.app.ActivityCompat already. My target API 23 and compile with API 23 also. How to solve it?
Below is the real code
public class MainActivity extends Activity {
public static final int MY_PERMISSION_SEND_SMS = 10;
public EditText edSMS, edPhone;
public Button btnSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edSMS = (EditText)findViewById(R.id.editText1);
edPhone = (EditText)findViewById(R.id.editText2);
btnSent = (Button)findViewById(R.id.button1);
onCheckPermission();
}
private void onCheckPermission() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermission(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSION_SEND_SMS);
}
else {
sentMessage();
}
}
private void sentMessage() {
btnSent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = edPhone.getText().toString();
String SMS = edSMS.getText().toString();
if(((phoneNumber.length() == 10) || (phoneNumber.length()==9)) && phoneNumber.length()>0){
SmsManager smsText = SmsManager.getDefault();
smsText.sendTextMessage(phoneNumber, null, SMS, null, null);
Toast.makeText(MainActivity.this, "SMS was sent successful", Toast.LENGTH_LONG).show();
edPhone.setText("");
edSMS.setText("");
} else {
Toast.makeText(MainActivity.this, "Please check your " + "phone number again",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode){
case MY_PERMISSION_SEND_SMS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
sentMessage();
}else{
Toast.makeText(this, "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)){
new AlertDialog.Builder(this).
setTitle("Request Permission SMS").
setMessage(" You must set permission to access this application").show();
}
}
break;
}
}
To solve the method ActivityCompat.checkSelfPermission() not found in Eclipse you can simply add android-support-compat.jar as taken from https://github.com/dandar3/android-support-compat/tree/28.0.0 to the libs folder of your Eclipse project and compile again.
just use support.v7 (import android.support.v7.app.AppCompatActivity;),this is well be rolved
by the way?why do you still use eclipse now?just use Android studio,it's better so much.
i have method for get runtime permission i searched for that long but still have no answer can anyone help me to modify my code ? cause its never show request dialog for get user permission after user accept permission move to next activity
here my code that i made but some how its never made a request
public class perm extends AppCompatActivity {
private static final int REQUEST_PERMISSION_SETTING = 200;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dash);
isPermissionGranted();
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PERMISSION_SETTING);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(permissions.length == 0){
return;
}
boolean allPermissionsGranted = true;
if(grantResults.length>0){
for(int grantResult: grantResults){
if(grantResult != PackageManager.PERMISSION_GRANTED){
allPermissionsGranted = false;
break;
}
}
}
if(!allPermissionsGranted){
boolean somePermissionsForeverDenied = false;
for(String permission: permissions){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
//denied
Log.e("denied", permission);
}else{
if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){
//allowed
Log.e("allowed", permission);
} else{
//set to never ask again
Log.e("set to never ask again", permission);
somePermissionsForeverDenied = true;
}
}
}
if(somePermissionsForeverDenied){
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Permissions Required")
.setMessage("You have forcefully denied some of the required permissions " +
"for this action. Please open settings, go to permissions and allow them.")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setCancelable(false)
.create()
.show();
}
} else {
switch (requestCode) {
//act according to the request code used while requesting the permission(s).
}
}
}
}