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.
Related
I want create a class called Permissions from below code and then call that in a click of a button. Because there is an #Override method in this activity and I don't know how to override methods inside a class. If I make a class for it the code would be much cleaner and easier to understand.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
final int REQUEST_CODE_FINE_LOCATION = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
// we are going to test weather the Location Permission is granted or not
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
textView.setText("Permission Granted...");
} else {
textView.setText("Permission is NOT granted");
}
}
public void requestPermission(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission is NOT granted
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(MainActivity.this)
.setMessage("We need permission for fine location")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_FINE_LOCATION);
}
})
.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_FINE_LOCATION);
}
} else {
// Permission is Granted
textView.setText("Permission Granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_FINE_LOCATION) {
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
textView.setText("Permission is Granted");
} else {
//Permission NOT granted
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
//This block here means PERMANENTLY DENIED PERMISSION
new AlertDialog.Builder(MainActivity.this)
.setMessage("You have permanently denied this permission, go to settings to enable this permission")
.setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
gotoApplicationSettings();
}
})
.setNegativeButton("Cancel", null)
.setCancelable(false)
.show();
} else {
//
textView.setText("Permission NOt granted");
}
}
}
}
private void gotoApplicationSettings() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
Source: https://github.com/trulymittal/RuntimePermission
Use TedPermission Library which is very easy to use and easy to handle .
Make a Function in separate class and use it anywhere you want
implementation 'gun0912.ted:tedpermission:2.2.3'
public void checkPermissions(Context context) {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Toast.makeText(context, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
Toast.makeText(context, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
TedPermission.with(context)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
}
https://github.com/ParkSangGwon/TedPermission
You can make interface hold all the methods and create abstract class implement the interface then make any classes that inherit from the abstract class read about liskov and segregation principles
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' am trying to list all the folders and files from user storage, I've declared the READ_EXTERNAL_STORAGE permission in android.manifest file but I don't what's wrong, I can't read the user storage
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, 123);
} else {
Log.d(TAG, "onCreate: Permission Granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case 123:
if (grantResults != null && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String path = "/";
File dir = new File(path);
if (dir.isDirectory()) {
Log.d(TAG, "dir: Yes, I am!");
}
if (dir.canRead()) {
Log.d(TAG, "dir: Read me!");
} else {
Log.d(TAG, "dir: you can't read me!");
}
if (dir.canWrite()) {
Log.d(TAG, "dir: use me!");
} else {
Log.d(TAG, "dir: You Can't write me");
}
}
}
}
log cat: D/MainActivity: onCreate: Permission Granted 2020-05-04
07:21:09.680 27634-27634/co.ak.externalstorage D/MainActivity: dir:
Yes, I am! 2020-05-04 07:21:09.680 27634-27634/co.ak.externalstorage
D/MainActivity: dir: you can't read me! 2020-05-04 07:21:09.680
27634-27634/co.ak.externalstorage D/MainActivity: dir: You Can't write
me
The "/" root directory is not readable since Android 7.
Why are you calling that user storage?
This question already has answers here:
How to make a phone call using intent in Android?
(21 answers)
How to make a phone call programmatically?
(10 answers)
How to make a phone call button in Android for Marshmallow
(3 answers)
How to ask permission to make phone call from Android from Android version Marshmallow onwards?
(7 answers)
Closed 4 years ago.
I used following code for phone call.But the call is not working .can anyone help me? I also given manifest Call Phone permission.
call = (TextView) findViewById(R.id.GuestPhoneNo1);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = call.getText().toString();
// Toast.makeText(Accepted_Details.this, no, Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + no));
/*if (ActivityCompat.checkSelfPermission(Accepted_Details.this, Manifest.permission.CALL_PHONE) != 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;
}*/
startActivity(callIntent);
}
You can use the following code,
I also add the permission popup for above marshmallow.
Uri call = Uri.parse("tel:" + mobile_number);
Intent surf = new Intent(Intent.ACTION_CALL, call);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(TrackActivity.this, Manifest.permission.CALL_PHONE)) {
ActivityCompat.requestPermissions(TrackActivity.this, new String[]{Manifest.permission.CALL_PHONE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
} else if (permissionStatus.getBoolean(Manifest.permission.CALL_PHONE, false)) {
AlertDialog.Builder builder = new AlertDialog.Builder(TrackActivity.this);
builder.setTitle("Need call Permission");
builder.setMessage("This app needs call permission.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getBaseContext(), "Go to Permissions to Grant call", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
ActivityCompat.requestPermissions(TrackActivity.this, new String[]{Manifest.permission.CALL_PHONE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
}
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(Manifest.permission.CALL_PHONE, true);
editor.apply();
} else {
startActivity(surf);
}
Even with having added the permissions in the manifest file you need to request for the permission before you run the code that makes the call
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MAKE_CALL_PERMISSION_REQUEST_CODE);
the whole thing could look like this
public class MainActivity extends AppCompatActivity {
private static final int MAKE_CALL_PERMISSION_REQUEST_CODE = 1;
private Button dial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dial = (Button) findViewById(R.id.dial);
final EditText numberToDial = (EditText) findViewById(R.id.number);
dial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = numberToDial.getText().toString();
if (!TextUtils.isEmpty(phoneNumber)) {
if (checkPermission(Manifest.permission.CALL_PHONE)) {
String dial = "tel:" + phoneNumber;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
} else {
Toast.makeText(MainActivity.this, "Permission Call Phone denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a phone number", Toast.LENGTH_SHORT).show();
}
}
});
if (checkPermission(Manifest.permission.CALL_PHONE)) {
dial.setEnabled(true);
} else {
dial.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MAKE_CALL_PERMISSION_REQUEST_CODE);
}
}
private boolean checkPermission(String permission) {
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case MAKE_CALL_PERMISSION_REQUEST_CODE :
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
dial.setEnabled(true);
Toast.makeText(this, "You can call the number by clicking on the button", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
I am trying to build an application where the user can send his/her location to the stored phone numbers in a sqlitedatabase. I tested the application where the user can send the location as a text message to just one phone number and it worked but now when I try to create a list of numbers and pass it as a parameter in sendTextMessage method of smsManager the location as a text message is not sent. I have tried out the given code below so far,
Code
public class Gps4Activity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {
private static final String LOG_TAG = "PlacesAPIActivity";
private static final int GOOGLE_API_CLIENT_ID = 0;
private GoogleApiClient mGoogleApiClient;
private static final int PERMISSION_REQUEST_CODE = 100;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
private TextView display;
private Button location_button,contacts_button;
//String number="xxxxxxxxxx";
ArrayList<String> numbers;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps4);
numbers=new ArrayList<>();
db = new UserDatabase(this).getReadableDatabase();
location_button=(Button)findViewById(R.id.show_button);
contacts_button=(Button)findViewById(R.id.view_button);
display=(TextView)findViewById(R.id.location_textview);
mGoogleApiClient = new GoogleApiClient.Builder(Gps4Activity.this)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.build();
location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mGoogleApiClient.isConnected()) {
if (ActivityCompat.checkSelfPermission(Gps4Activity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Gps4Activity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
ActivityCompat.requestPermissions(Gps4Activity.this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
callPlaceDetectionApi();
}
});
contacts_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Gps4Activity.this,DetailsActivity.class);
startActivity(intent);
}
});
}
public ArrayList<String> getContacts(){
Cursor cursor=db.rawQuery("SELECT * FROM "+UserDatabase.TABLE_NAME,null);
while (cursor.moveToNext()){
String contact=cursor.getString(cursor.getColumnIndex(UserDatabase.NUMBER));
numbers.add(contact);
}
return numbers;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(LOG_TAG, "Google Places API connection failed with error code: "
+ connectionResult.getErrorCode());
Toast.makeText(this,
"Google Places API connection failed with error code:" +
connectionResult.getErrorCode(),
Toast.LENGTH_LONG).show();
}
#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) {
callPlaceDetectionApi();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
break;
}
}
private void callPlaceDetectionApi() throws SecurityException {
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(LOG_TAG, String.format("Place '%s' with " +
"likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
display.setText(placeLikelihood.getPlace().getAddress().toString());
messageSending(placeLikelihood.getPlace().getAddress().toString());
break;
}
likelyPlaces.release();
}
});
}
public void messageSending(String message){
SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage(number, null, message, null, null);
getContacts();
smsManager.sendTextMessage(String.valueOf(numbers),null,message,null,null);
Toast.makeText(getApplicationContext(), "SMS sent."+String.valueOf(numbers),
Toast.LENGTH_LONG).show();
}
}
The commented lines are the ones when I tried to test the application with just one phone number. Also, suppose initially there is just one phone number in sqlitedatabase , as many times I click the location_button that many times the arraylist grows it's size. For example , initially if the arraylist has elements [xxxxxx] next time I click the location_button the arraylist will now have [xxxxxx,xxxxxx].
Can anyone help me solving this issue?
Since the sendTextMessage() method only can take one number at a time, you need to execute this method for each number in the list.
That being said you should 'loop' through that List. Like this:
for (String number : numbers) {
smsManager.sendTextMessage(numbers, null, message, null, null);
}
What it basically is saying is:
"Allright, let's take number one, sendTextMessage to number one, and I will keep doing this until I am done."