I am new to android dev and little knowledge of java.I want to know how to inflate a layout from service using SYSTEM_ALERT_WINDOW
public void checkDrawOverlayPermission() {
/* check if we already have
permission to draw over
other apps */
if(android.os.Build.VERSION.SDK_INT > 23) {
if (!Settings.canDrawOverlays(this))
{
/* if not construct intent to request permission */
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
/* request permission via start activity for result */
startActivityForResult(intent, REQUEST_CODE);
}
else {
createOnTopView();
}}}}
I used that to get permission↑↑↑
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/* check if received result code
is equal our requested code for draw permission */
if (requestCode == REQUEST_CODE && android.os.Build.VERSION.SDK_INT > 22) {
/* if so check once again if we have permission */
if (Settings.canDrawOverlays(this)) {
createOnTopView();
}
}
}
after I run this on my phone Teckno k7 ,android 6.0
It runs well buh can't run on my friend's phone Techno F2.it crashes on his phone.
Please help me.
Related
I need to have my app draw over other apps, and I tried getting SYSTEM_ALERT_WINDOW permission shown below.
public class excessiveusageactivity extends AppCompatActivity {
static final int REQUEST_OVERLAY_PERMISSION = 1; //request code
TextView result;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
result = findViewById(R.id.result);
if (requestCode == REQUEST_OVERLAY_PERMISSION) {
if (Settings.canDrawOverlays(this)) {
Toast permissionok = Toast.makeText(this, "permission granted!", Toast.LENGTH_SHORT);
permissionok.show();
//permission granted do stuff
result.setText("yay");
}else{
Toast permissionnotgrantedtoast = Toast.makeText(this,"permission request failed, try again!", Toast.LENGTH_LONG);
permissionnotgrantedtoast.show();
//permission not granted
result.setText("not granted");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_excessiveusageactivity);
if(
Settings.canDrawOverlays(this)
) {
// ask for overlay permission
Intent requestoverlaypermissionintent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(requestoverlaypermissionintent, REQUEST_OVERLAY_PERMISSION);
result.setText("here");
}
}
}
I got this code from here by user Jayman Jani.
I wish to make a custom system alert popup when the user uses an app for X minutes/hour consecutively, but I can't seem to find any information on how to set up this popup. I am quite new to all this so it would be great if someone can explain it mostly step-by-step. Thank you!
I going to change some system setting in android and i use this code :
ContentResolver cr = getContentResolver();
Settings.System.putInt(cr, Settings.System.HAPTIC_FEEDBACK_ENABLED, 0);
this code used for change screen Brightness use Brightness sensor,
but in android 6 I get this exception
java.lang.SecurityException: com.vpn.sabalan was not granted this permission: android.permission.WRITE_SETTINGS.
i can use this method to get permission from user , but i need get permission programmetically can any one help me ?
private void showBrightnessPermissionDialog( )
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !android.provider.Settings.System.canWrite(this))
{
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:"+getPackageName()));
startActivity(intent);
}
}
Update Android Marshmallow and Higher
You can start System settings to grant Write System Settings. Once this permission is grant by user you can set brightness without any issues
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
}
Follow the step by step provided in documentation. It is very thorough.
https://developer.android.com/training/permissions/requesting.html
All you have to do is request permission, and override the callback for onRequestPermissionsResult to check if you got it or not. If you did, then you are good to go. You still need it in your manifest though or it won't work.
UPDATE to show details based on your comments.
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
private static final int REQUEST_WRITE_PERMISSION = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doFileWork();
}else{
//handle user denied permission, maybe dialog box to user
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
} else {
doFileWork();
}
}
}
There are also many good libraries out there that wrap this callback context if you really want to go that route, but it isn't that complex. Make sure you also have write permission in your Manifest.
I am writing a simple inventory management app that takes a picture of items to be logged. So the expected behaviour is that users hit a button to launch the camera, take a picture and return to the app to enter text information. But I keep getting the following Security Exception error
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.media.action.IMAGE_CAPTURE cmp=com.android.camera/.Camera }
from ProcessRecord{734dbfd 22169:com.virgo19.tinni.teatracker/u0a58}
(pid=22169, uid=10058) with revoked permission android.permission.CAMERA
I have looked around the web for days and there doesn't seem to be any solution since I am already following the Android Developer instructions. Including the instruction about asking for permission at runtime. Code fragments below,
//Code calling camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, RETURN_FROM_CAMERA);
}
//On activity return request fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RETURN_FROM_CAMERA && data != null){
//Check permissions
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if(permissionCheck == PackageManager.PERMISSION_GRANTED){
//Permission is okay, so get on with getting image from Camera
Bundle extras = data.getExtras();
tinImage = (Bitmap) extras.get("data");
//set image view
setImage();
} else if (permissionCheck != PackageManager.PERMISSION_GRANTED){
//Permission not granted, ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
}
Can anyone see why this keeps crashing? Thanks!
You need to request the CAMERA permission before taking the picture via startActivityForResult(). Your current code attempts to request this permission after taking the picture.
I am working on restoring SMS on KITKAT. Referring to this article I have added the things which are required to set my app as default app for SMS. After adding all required things in manifest file I have write the following code:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(mContext);
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, mContext.getPackageName());
mContext.startActivity(intent);
}
The above code shows this dialog but I am unable to get the result from this activity/dialog either user clicked on Yes or No because I want to add listener or get any code which should represent that the user clicked on these buttons.
Thanks.
One way to do this is to fire the Intent with startActivityForResult(), and then check the resultCode in the onActivityResult() method. Please note that I've changed the code in the example to run in an Activity's Context.
private static final int DEF_SMS_REQ = 0;
private String mDefaultSmsApp;
...
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
mDefaultSmsApp = Telephony.Sms.getDefaultSmsPackage(this);
if (!getPackageName().equals(mDefaultSmsApp))
{
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivityForResult(intent, DEF_SMS_REQ);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case DEF_SMS_REQ:
boolean isDefault = resultCode == Activity.RESULT_OK;
...
}
}
As mentioned in a comment below, apparently checking the result code is not 100% reliable. A safer check is to simply compare your app's package name to the current default in onActivityResult(). There's no need to check the result code at all, like the answer linked in the comment shows.
String currentDefault = Sms.getDefaultSmsPackage(this);
boolean isDefault = getPackageName().equals(currentDefault);
The way you can react on "yes" button click:
private String mDefSmsPackage;
#Override
public void onCreate(#Nullable Bundle state) {
//...
mDefSmsPackage = Telephony.Sms.getDefaultSmsPackage(getActivity())
}
#Override
public void onResume() {
super.onResume();
String newDefSmsPkg = Telephony.Sms.getDefaultSmsPackage(getActivity());
if (!TextUtils.equals(mDefSmsPackage, newDefSmsPkg)) {
mDefSmsPackage = newDefSmsPkg;
//ON DEF SMS APP CAHNGE...
}
}
is it possible to get the phonenumber of each device programmatically?
I tried this code:
TelephonyManager manager =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = manager.getLine1Number();
This works fine with some providers. Unfortunately it does not work with each provider. So i am looking for a trick or work around to get the phonenumber of the device. Is there a solution or is it impossible because the number is not stored on the sim card?
The method you are using is the only one part of the SDK to do this, and only works on devices where the number is stored on the SIM card, which only some carriers do. For all other carriers, you will have to ask the user to enter the phone number manually, as the number is simply not stored anywhere on the device from where you can retrieve it.
You can try to send specific SMS to ISP.
For example, in Beijing(China), when you send SMS "501" to 10001, you will get your phone number in the received message.
Then you only need to know how to send SMS and register a BroadcastReceiver to receive the message.
Now its not require any permission to get phone number
use Play Services API without the permission and hacks. Source and Full example.
build.gradle (version 10.2.x and higher required):
compile "com.google.android.gms:play-services-auth:$gms_version"
In your activity (the code is simplified):
enter image description here
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.CREDENTIALS_API)
.build();
requestPhoneNumber(result -> {
phoneET.setText(result);
});
}
public void requestPhoneNumber(SimpleCallback<String> callback) {
phoneNumberCallback = callback;
HintRequest hintRequest = new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient,
hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), PHONE_NUMBER_RC, null,
0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Logs.e(TAG, "Could not start hint picker Intent", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHONE_NUMBER_RC) {
if (resultCode == RESULT_OK) {
Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
if (phoneNumberCallback != null){
phoneNumberCallback.onSuccess(cred.getId());
}
}
phoneNumberCallback = null;
}
}