How to enable vibration on touching every button in app - android

In my settings menu i have used a switch when i turn it on i want every button in-app to vibrate and when i turn the switch off i want every button in-the app to not vibrate.
The following is the code i have tried so far.
switch2!!.setOnCheckedChangeListener { buttonView, isChecked ->
if (switch2!!.isChecked) {
switch2!!.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
else {
vibrator.cancel()
}
}

You can do like this.
Using SharedPreference . https://developer.android.com/training/data-storage/shared-preferences
Once you stored the key, you can use the key at the other activity/fragment.
At onCreate , you get the value from SharedPreference.
You use variable to check it first before click the button.
If yes, then vibrate it. Refer to this. https://stackoverflow.com/a/52990380/9346054
**Don't forget to declare at AndroidManifest as the refer above.
<uses-permission android:name="android.permission.VIBRATE" />
Example.
Here at onCreate
val vibe = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
val isVibrate = sharedPref.getInt(getString(R.string.is_vibrate), defaultValue)
And then inside onClick button
if (isVisible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
vibrator.vibrate(200)
}
}

you need to add this permission first
<uses-permission android:name="android.permission.VIBRATE"/>
and next you can use this fun for vibrate mobile
fun vibratePhone(context: Context?, milliseconds: Int) {
val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(
VibrationEffect.createOneShot(
milliseconds,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
} else {
vibrator.vibrate(milliseconds)
}
}

Related

How can I distinguish if the user request the permission for the first time or he clicked on the Never Ask Again button?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected. In this UI,
// include a "cancel" or "no thanks" button that allows the user to
// continue using your app without granting the permission.
} else {
if (requireContext().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
openCamera();
else {
//How can I know here if this is was the first time to request the permission or he pressed on Never Ask Again button before?
//Run this code if that was the first time to request the permission -> requestPermissionLauncher.launch(Manifest.permission.CAMERA);
//Run this code if he pressed on Never Ask Again button -> new AlertDialog(context)... etc - The dialog contains a button that moves the user to app settings to enable the permission
}
}
} else
openCamera();
How can I distinguish if the user request the permission for the first time or he clicked on the Never Ask Again button?
A boolean value can be used to check if the user has denied permission earlier or not.
Add the following methods to the above file or create a utility file.
public static boolean neverAskAgainSelected(final Activity activity, final String permission) {
final boolean prevShouldShowStatus = getRatinaleDisplayStatus(activity,permission);
final boolean currShouldShowStatus = activity.shouldShowRequestPermissionRationale(permission);
return prevShouldShowStatus != currShouldShowStatus;
}
public static void setShouldShowStatus(final Context context, final String permission) {
SharedPreferences genPrefs = context.getSharedPreferences("GENERIC_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = genPrefs.edit();
editor.putBoolean(permission, true);
editor.commit();
} public static boolean getRatinaleDisplayStatus(final Context context, final String permission) {
SharedPreferences genPrefs = context.getSharedPreferences("GENERIC_PREFERENCES", Context.MODE_PRIVATE);
return genPrefs.getBoolean(permission, false);
}
Call inside the permission Request place:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected. In this UI,
// include a "cancel" or "no thanks" button that allows the user to
// continue using your app without granting the permission.
} else {
if (requireContext().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
openCamera();
else {
if(neverAskAgainSelected(this,Manifest.permission.CAMERA){
// new AlertDialog(context)...
}
else{
requestPermissionLauncher.launch(Manifest.permission.CAMERA);
}
}
}
} else{
openCamera();
}

Unlock android device not working while call ACTION_CALL intent

I am receiving a push notification, On that, calling a foreground service.
From the service, I am calling one Activity.
Here, I have 2 functionality.
1. Sound alarm for emergency
2. Call using ACTION_CALL.
Both are working fine if device unlocked.
But if a device is locked with password or pattern it did not work when push receives.
Below code to unlock the device. this method is called from onStart.
private void unlockDevice() {
KeyguardManager loKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
Window loWindow = this.getWindow();
if (Common.isAboveAPI27()) {
setShowWhenLocked(true);
setTurnScreenOn(true);
} else if (Common.isAboveAPI26()) {
loWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
loWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
dismissKeyguard(loKeyguardManager);
} else {
if (loKeyguardManager != null) {
KeyguardManager.KeyguardLock loKeyguardLock = loKeyguardManager.newKeyguardLock("FullWakeUps");
loKeyguardLock.disableKeyguard();
}
loWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // Deprecated in 26
loWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // Deprecated in 27
loWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); // Deprecated in 27
}
//Keep screen on
loWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void dismissKeyguard(KeyguardManager loKeyguardManager) {
if (loKeyguardManager != null) {
loKeyguardManager.requestDismissKeyguard(SOSCallAndAlarmActivity.this, new KeyguardManager.KeyguardDismissCallback() {
#Override
public void onDismissError() {
super.onDismissError();
Log.i(TAG, Build.VERSION.SDK_INT + " : onDismissError");
}
#Override
public void onDismissSucceeded() {
super.onDismissSucceeded();
Log.i(TAG, Build.VERSION.SDK_INT + " : onDismissSucceeded");
}
#Override
public void onDismissCancelled() {
super.onDismissCancelled();
Log.i(TAG, Build.VERSION.SDK_INT + " : onDismissCancelled");
}
});
}
}
The below method is call in onDestroy to reenable the lock:
private void reEnabledKeyguard() {
KeyguardManager loKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (loKeyguardManager != null) {
KeyguardManager.KeyguardLock loKeyguardLock = loKeyguardManager.newKeyguardLock("FullWakeUps");
loKeyguardLock.reenableKeyguard();
}
Window loWindow = this.getWindow();
loWindow.addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
}
Code to initiate the call.
public void callOnNumbers(String fsPhoneNumber) {
Intent loCallIntent = new Intent(Intent.ACTION_CALL);
loCallIntent.setData(Uri.parse("tel:" + fsPhoneNumber));
//callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // tried this but not helped.
if (ActivityCompat.checkSelfPermission(CallAndAlarmActivity.this,
android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "call phone permission not granted");
return;
}
startActivity(loCallIntent);
}
Strange is when this method opens the call screen blink and again displays the password screen on lock screen simply press back button I can see the call screen.
I need to know one more thing, even I set all app killing option and disabled battery optimization. the same code did not execute on push receive.
When device inactive half an hour and if push receives, the above code did not even turn on light. when I click on the lock/unlock button I can see my screens properly. even I press it after 30 seconds of push receives time.
The problem facing from android N.
Additional
When the ACTION_CALL intent calls it to execute my activities onPause and I did not add any code in onPause and I can see one error in logcate
2020-04-27 16:23:47.400 25826-25826/app.safety E/ActivityThread: Performing stop of activity that is already stopped: {app.safety/app.safety.CallAndAlarmActivity}
java.lang.RuntimeException: Performing stop of activity that is already stopped: {app.safety/app.safety.CallAndAlarmActivity}
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4089)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4177)
at android.app.ActivityThread.-wrap24(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1648)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
2020-04-27 16:23:47.400 25826-25826/app.safety E/ActivityThread: ActivityClientRecord{paused=true, stopped=true, hideForNow=false, startsNotResumed=false, isForward=false, pendingConfigChanges=0, onlyLocalRequest=false, preserveWindow=false, Activity{resumed=false, stopped=true, finished=false, destroyed=false, startedActivity=false, temporaryPause=false, changingConfigurations=false}}
Thanks
I wonder if it has something to do with the Background Execution Limit. in Android. I would recommend looking at this article.
https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c
I hope this is of any help.

How to check if "verify app" is enabled or disabled programmatically

I've a security requirement to alert users if google's "verify app" is disabled on app launch. The problem is that I dont know any way to check whether "verify app" is disabled or not.
I tried to use the code below, but it's always returning 1.
int verifierInt = -1;
if (Build.VERSION.SDK_INT >= 17) {
verifierInt = Settings.Global.getInt(context.getContentResolver(), "package_verifier_enable", -1);
} else if (Build.VERSION.SDK_INT >= 14) {
verifierInt = Settings.Secure.getInt(context.getContentResolver(), "verifier_enable", -1);
} else {
// No package verification option before API Level 14
}
boolean isVerifyAppEnabled = verifierInt == 1;
Also, as a requirement, want user to be navigated to the "verifiy app" settings if this feature is disabled.
You should check like this:
Settings.Global.getInt(context.getContentResolver(), "verifier_verify_adb_installs", -1);
Reading preferences, won't help anymore as android don't update preferences now. So basically reading preferences value for google Verify won't work.
Please use below SaftyNet callbacks to verify google protect.
SafetyNet.getClient(context)
.isVerifyAppsEnabled()
.addOnCompleteListener(new OnCompleteListener<SafetyNetApi.VerifyAppsUserResponse>() {
#Override
public void onComplete(#NonNull Task<SafetyNetApi.VerifyAppsUserResponse> task) {
---
}
});

How to get system vibration data android?

Is it possible to get system vibration pattern as a long[] array? For example standard SMS vibration pattern or current selected in preferences SMS vibration signal.
I don't think it's possible to get the default patterns of your current device as a long[] array. You'll probably have to do a trial and error approach on this. And set a bunch of if's on your code to choose a different vibration pattern depending on the device or cellphone brand.
Something like:
YourActivity.java
import android.os.Vibrator;
private long[] patt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String man = android.os.Build.MANUFACTURER;
if (man.equals("SAMSUNG")) {
patt = {0l,300l,50l,350l};
}
else {
patt = {0l,200l,100l,100l};
}
vibrate(patt);
}
private void vibrate(long[] pattern) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (v.hasVibrator()) {
v.vibrate(pattern,-1);
}
}
And don't forget to add the permission to vibrate.
AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>
Refer to this link for android.os.Build information.

How to open or expand status bar through intent?

I am making a home application and I think that it will be suitable if I use a fullscreen and not show the status bar. So now I want to be able to open or expand the status bar with a button on the menu, similar to the way some default home applications have in the menu. I know its possible since the default home does it. Is this done through an intent? If so can I have the code for it. If not well then I would appreciate it if you guys showed me how. Thanks!
See if this helps and let me know...
try{
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method expand = statusbarManager.getMethod("expand");
expand.invoke(service);
}
catch(Exception ex){
....
}
uses permission : "android.permission.EXPAND_STATUS_BAR";
The code below works for me:
boolean shown = true;
private void showHide() {
Window w = this.getWindow();
if(shown)
{
w.setFlags(0,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else
{
w.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
shown=!shown;
}
This one worked for me:
manifest:
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>
Code:
// https://gist.github.com/XinyueZ/7bad2c02be425b350b7f requires permission: "android.permission.EXPAND_STATUS_BAR"
#SuppressLint("WrongConstant", "PrivateApi")
#JvmStatic
fun setExpandNotificationDrawer(context: Context, expand: Boolean) {
try {
val statusBarService = context.getSystemService("statusbar")
val methodName =
if (expand)
if (Build.VERSION.SDK_INT >= 17) "expandNotificationsPanel" else "expand"
else
if (Build.VERSION.SDK_INT >= 17) "collapsePanels" else "collapse"
val statusBarManager: Class<*> = Class.forName("android.app.StatusBarManager")
val method: Method = statusBarManager.getMethod(methodName)
method.invoke(statusBarService)
} catch (e: Exception) {
e.printStackTrace()
}
}
However, someone wrote it doesn't work on all devices and Android versions (here), so I wrote a request to add official API for this, here.

Categories

Resources