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!
Related
I have an Activity which makes use of KeyguardManager.
The intention is to disallow the user to use the app, if they are unable to successfully supply their credentials.
Though the keyguard intent appears at the start of the app, pressing the device back button moves the intent away, showing the activity which started it.
Overriding the onBackPressed does not seem to help, as it isn't associated with the intent.
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (km.isKeyguardSecure()) {
setShowWhenLocked(true);
Intent i = km.createConfirmDeviceCredentialIntent("Authentication required", "password");
startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION);
}
}
What if you use finish() after startActivity() ?
EDIT:
Add finish() on your onActivityResult() if the pattern is false.
What you want to achieve can be done using a "Staging" Activity. For example, you can have a LoginActivity that will check if the user is authenticate or not then from there decide where to redirect him.
The LoginActivity should look something like this, of course you need to adapt it to your business logic :
public class LoginActivity extends AppCompatActivity {
private static final int CODE_AUTHENTICATION_VERIFICATION = 24;
private boolean isFirstLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
isFirstLaunch = false;
//startActivityForResult With your intent to authenticate the user
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CODE_AUTHENTICATION_VERIFICATION){
Log.i("LOGIN", "return from key guard");
//Check the data and decide if you redirect the user to main activity or not
}
}
#Override
protected void onResume() {
super.onResume();
if(!isFirstLaunch){
Log.i("LOGIN", "resume not first launch");
// the user tried to cancel the authentication either present him with the authentication process again or finish() the activity
}
}
}
Please, N/B: Overriding the onBackPressed does help only when you create a conditional statement controlled by a boolean variable in the onBackPressed method and call it in the onActivityResult i.e when the resultCode != RESULT_OK. Another option is to exit the app when resultCode != RESULT_OK (moveTaskToBack(true)) Here is what I mean below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == INTENT_AUTHENTICATE) {
if (resultCode == RESULT_OK) {
//do something you want when pass the security
} else //resultCode != RESULT_OK
//Option 1 Ensure you override onBackPressed() with a conditional
//statement controlled by a boolean variable.
onBackPressed();
//Option 2
moveTaskToBack(true); //Exit app when a user click the back button.
}
}
I'm trying to just sign a user to the app to be able to use Google Drive API, but in my activityResults I always get the else statement and that means the user is not authorized or the sign in have failed. Why might this be? I have followed the official docs.
Here is my code:
private static final int REQUEST_CODE_SIGN_IN = 0;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
/**
* Starts the sign-in process and initializes the Drive client.
*/
private void signIn() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == Activity.RESULT_OK) {
// App is authorized, you can go back to sending the API request
Log.e("SignIn", "App autorizada");
} else {
// User denied access, show him the account chooser again
Log.e("SignIn", "App No Autorizada");
finish();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Solved my own problem pasting the SHA1 and package name into credentials in my google console, it seemed i was doing something wrong with the credentials.
Code looks fine. Check if you have added google_services.json file in the project. Also check if th SHA1 key is correct.
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 have a WebActivity that sets a JavascriptInterface for a WebView, on the Interface I have created various methods to be called with Javascript for different tasks, one of them is to send a file through Bluetooth.
The file sends just fine, but I want to inform the user when the file has already been accepted and transmited completely on the other end.
I am trying to use onActivityResult on my main WebActivity and also have tried on the separate class that handles the Bluetooth transmission and has a method called on the JavascriptInterface but I am not getting any callback results after the file is succesfully sent:
//First attempt
public class WebActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//some code here
//Here I set the interface
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == 0) {
//This message is shown after the file transfer has started but no
//finished
Toast.makeText(this, "File Sent", Toast.LENGTH_SHORT).show();
if(resultCode == Activity.RESULT_OK){
//It doesn't work here either I always get Activity.RESULT_CANCELED (0)
//flag afer the file transfer has started
}
}
}
}
//Second Attempt
public class BluetoothTasks {
//code here
private void startTransferIntent() {
//some more code here
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
File file_to_transfer = new File(Environment.getExternalStorageDirectory() +
"/txtTransfer.txt");
intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file_to_transfer));
//some more code here
Activity act = (Activity) mContext;
act.startActivityForResult(intent, TRANSFER_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == TRANSFER_RESULT) {
//Not working here either
//code that is not executed
}
}
}
Could you please tell me if there is a way to do this and if so how would be accomplished?. Thank you.
Please help me. I need to get activity result from GCM receiver, the code is below
On MainActivity.class
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//PARSE RESULT CODE
if (resultCode == RESULT_OK){
Toast.makeText(_context,"WAS LOGIN", Toast.LENGTH_LONG).show();
mainProgram();
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(_context,"WAS NOT LOGIN", Toast.LENGTH_LONG).show();
showLoginForm();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(SampleList.THEME); // Used for theme switching in samples
super.onCreate(savedInstanceState);
Intent intent = new Intent(MainActivity.this, LoginProc.class);
startActivityForResult(intent, 0);
}
private void mainProgram(){
setContentView(R.layout.mainlayout);
}
and in LoginProc.class
#Override
protected void onCreate(Bundle savedInstanceState) {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar.register(this, SENDER_ID);
registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
this.regId = GCMRegistrar.getRegistrationId(this);
GCMRegistrar.register(this, SENDER_ID);
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
Toast.makeText(getApplicationContext(),"New Message On MHandled:"+newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
//hide progress
showProgress(false);
//set result vars for this intent
Intent i=new Intent();
LoginProc.this.setResult(RESULT_OK,i);
//Intent i = new Intent();
//setResult(RESULT_CANCELED, i);
finish();
}
};
and the result is always show ToastText "WAS NOT LOGIN" even after event GCM is success (Toas "New Message On MHandled" displayer).
Need right direction here, thanks a lot
Make sure you have given all needed permission and this receives messages via GCMIntentService which would have to register in Manifest.
Check this link
This will tell the steps for GCM registration and getting push messages from server.