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();
}
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);
}
I'm trying to set up an activity that when accessed will tell the user how many GPS satellites there are available and how strong the signal is, but since i can't even get the satellite number i'm kinda stuck.
And now that i have tried over a month to get it to work, by making the code to do it in the activity itself or up to several classes that extends and or implements the GpsStatus, GpsStatus.Listener or the LocationManager, i'm at a loss anyone got any ideas?
All of this code is in the activity itself.
I have cut out all uses of classes and code i've tried but couldn't get to work, this is the closest i have gotten and none of the counting variables returns anything but zero.
#TargetApi(Build.VERSION_CODES.N)
public void countSatellites(){
int satellites = 0;
int satellitesInFix = 0;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GpsStatus status = locationManager.getGpsStatus(null);
Iterable sats = status.getSatellites();
Iterator satI = sats.iterator();
int count = 0;
while(satI.hasNext()){
GpsSatellite gpssatellite = (GpsSatellite) satI.next();
if (gpssatellite.usedInFix()){
count++;
}
}
int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
if (sat.usedInFix()) {
satellitesInFix++;
}
satellites++;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkLocationPermission()) {
countSatellites();
}
} else {
}
return;
}
}
}
public boolean checkLocationPermission() {
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connections);
LocationUpdateService locationService = new LocationUpdateService();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
In a another file
public class LocationUpdateService extends Service implements GpsStatus.Listener{
public void onCreate(){
Log.i("on create", "success");
super.onCreate();
registerGpsStatusListener();
}
private void registerGpsStatusListener() {
Log.i("gps listener", "success");
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(this);
}
#Override
public void onGpsStatusChanged(int event) {
Log.i("gps change", "success");
switch (event) {
case GpsStatus.GPS_EVENT_STARTED:
Log.e("gps started", "onGpsStatusChanged started");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.e("gps stopped", "onGpsStatusChanged stopped");
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.e("gps first", "onGpsStatusChanged first fix");
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.e("gps status", "onGpsStatusChanged status");
break;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.i("on bind", "success");
return null;
}
public void onLocationChanged(Location location) {
Log.i("location change", "success");
}
}
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()
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.