How to enable vibration when screen timeout occurs? - android

I want the device to start vibrating for some amount of time when screen timeout option enables(when the light dims, before the screen shuts off).I know how to set up both functions individually, but I can't seem to manage to get them in the right order for this to work, so I need your help. Thanks and cheers!

Use the vibrator class to initiate vibration
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Vibrator vib = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
vib.vibrate(5);
}
}, 30000); //30 sec
Edit:
Don't forget as I did to declare in the app manifest file
<uses-permission android:name="android.permission.VIBRATE"/>

Related

How to enable and disable vibration mode programmatically

I need to enable and disable the vibration mode of mobile when user turns off and turns on the switch button .
I have tried the code below, but it's not working:
AudioManager myAudioManager;
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Toast.makeText(this, "in setting "+(myAudioManager.getMode()==AudioManager.RINGER_MODE_VIBRATE),1).show();
if(myAudioManager.getMode()==AudioManager.RINGER_MODE_VIBRATE) {
//myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
}
else
{
//myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
}
We can enable and disable the silent mode programmatically by using AudioManager:
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
for setting silent mode :
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
For normal mode :
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
First of all use this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>
Now
public void startVibrate(View v) {
long pattern[] = { 0, 100, 200, 300, 400 };
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, 0);
}
public void stopVibrate(View v) {
vibrator.cancel();
}
Vibrate pattern
public abstract void vibrate (long[] pattern, int repeat)
Pattern for vibration is nothing but an array of duration's to turn ON and OFF the vibrator in milliseconds. The first value indicates the number of milliseconds to wait before turning the vibrator ON. The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off. Subsequent values, alternates between ON and OFF.
long pattern[]={0,100,200,300,400};
If you feel not to have repeats, just pass -1 for 'repeat'. To repeat patterns, just pass the index from where u wanted to start. I wanted to start from 0'th index and hence I am passing 0 to 'repeat'.
vibrator.vibrate(pattern, 0);
myAudioManager.setVibrateSetting();
This method was deprecated in API level 16.
you can use this one:
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT)
RINGER_MODE_SILENT : will mute the volume and will not vibrate.
RINGER_MODE_VIBRATE: will mute the volume and vibrate.
RINGER_MODE_NORMAL: will be audible and may vibrate according to user settings.
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}

how to cancel a vibration in alert box?

I'm creating a app that popup a alert box that have to vibrate until the user click ok or cancel
my app vibrate good when i open the alert box but when i click ok or cancel app crash
this is coding i used for creating a alert box with vibrate
Vibrator v;
button = (Button) findViewById(R.id.buttonAlert);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
vibration();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Your Title");
alertDialogBuilder.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
v.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
v.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
and this is a vibrate method
public void vibration()
{
Vibrator v = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
long[] pattern = { 0, 3000, 3000 };
v.vibrate(pattern, 0);
// v.vibrate(5000);
}
I am getting error when i used Vibrator.cancel(); or v.cancel(); can any one help me
Try using vibrate(3000); which is equivalent to let the device vibrate for 3 seconds, insted of trying to cancel a started service.
Try to cancel the vibrator before exiting from the Dialog. See Vibrator class for more details.
try like below.....
Vibrator v = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
long[] pattern = {0,1000,1000};
v.vibrate(pattern, -1);
set the alert flag from default to
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL
This way, the notification will not cause vibrate.
If you want to make it vibrate also, you will have to give permission in manifest file for it
Make sure that application seeks vibrate permission in manifest. The application crash is due to the reason that your application does not have permission to vibrate the phone.
Here is the code
<uses-permission android:name="android.permission.VIBRATE" />
Edit:
I think you what you need is something different. You need a way to stop vibration after starting it.
Vibration service runs in a different context and hence you might not be able to communicate with it directly. There are several ways to do that but I am suggesting another easy way.
Instead of running vibration continuously, try running it for a small interval and put a timer in your dialog that will fire the vibration on after some time.
This way, you will not have to stop the vibration. As soon as the dialog is dismissed, the timer will stop firing and vibrate will stop. You will not need to explicitly turn off the vibration.
in your code you have v.cancel(); but as i can see this variable is not initialized, you are using another variable inside the function vibration() try to cancel an initialized variable of vibrate .
use this function
public Vibrator vibration() {
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = { 0, 3000, 3000 };
v.vibrate(pattern, 0);
// v.vibrate(5000);
return v;
}
and start the vibration like that
final Vibrator v = vibration();
P.S. i know it is an old question but maybe someone want the answer.

Allow phone to vibrate when screen turns off

I am looking for a way to allow my program to make the phone vibrate after the screen has turned off from timing out. I have done lots of research, and have not found something that works. I have looked at the PowerManager class and more specifically the WakeLock mechanism. From the sound of many posts, I would need to use the PARTIAL_WAKE_LOCK variable of the WakeLock class.
PARTIAL_WAKE_LOCK - Wake lock that ensures that the CPU is running.
However, I cannot get it to vibrate the phone when the screen turns off. I know I am using the WakeLock correctly because I can get SCREEN_DIM_WAKE_LOCK to work. Is PARTIAL_WAKE_LOCK what I am looking for?
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// This example will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200; // Length of a Morse Code "dot" in milliseconds
int dash = 500; // Length of a Morse Code "dash" in milliseconds
int short_gap = 200; // Length of Gap Between dots/dashes
int medium_gap = 500; // Length of Gap Between Letters
int long_gap = 1000; // Length of Gap Between Words
long[] pattern = {
0, // Start immediately
dot, short_gap, dot, short_gap, dot, // s
medium_gap,
dash, short_gap, dash, short_gap, dash, // o
medium_gap,
dot, short_gap, dot, short_gap, dot, // s
long_gap
};
// Only perform this pattern one time (-1 means "do not repeat")
v.vibrate(pattern, -1);
} else {
// YOUR CODE
}
}
note u must Add the uses-permission line to your Manifest.xml file, outside of the block.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<uses-permission android:name="android.permission.VIBRATE"/>
note : you must also test this code on a real phone , emulator can't viberate
For me the solution was to use directly vibrate without patterns, so I don't have to use PowerManager to wake lock.

Stop the system vibration on receive call in android

i made a BroadcastReceiver that is listening for changes in the PHONE_STATE. in the onReceive method, i'd like to turn off the system vibrator. i tried different approaches, but non of them worked so far.
AudioManager audioManager = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
systemVibration = audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
or
Vibrator vib = (Vibrator)ctx.getSystemService(Context.VIBRATOR_SERVICE);
vib.cancel();
or
System.putInt(ctx.getContentResolver(), System.VIBRATE_ON, 0);
or all of them together.
the first approach with the AudioManager really changes the system setting for the vibration, but it does not affect the currently ongoing one.
any ideas?
Simon
Stopping Vibration started by other process is not allowed in android now and thus this hack could stop Vibration or it will give you a feel that it has stopped vibration.
long timea = System.currentTimeMillis();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
while ((System.currentTimeMillis() - timea) < 15000) {
v.vibrate(1);
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
Try this: (borrowed and modified from Android Source)
AudioManager am = Context.getSystemService(Context.AUDIO_SERVICE);
boolean vibeInSilent = false;
int callsVibrateSetting = AudioManager.VIBRATE_SETTING_OFF;
Settings.System.putInt(getContentResolver(),
Settings.System.VIBRATE_IN_SILENT,
vibeInSilent ? 1 : 0);
//mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//or (not sure which one will work)
//mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
am.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
callsVibrateSetting);

Turn off screen on Android

I am trying to turn on and off the display after a certain action happens (Lets just worry about turning the screen off for now). From what I understand from wake lock, this is what I have:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
When I read other posts on stackoverflow and else where, they seem to tell me that PARTIAL_WAKE_LOCK will turn the screen off. But if I read the SDK it says that it will only allow the screen to be turned off. I think this isn't right.
There are two choices for turning the screen off:
PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
// Choice 1
manager.goToSleep(int amountOfTime);
// Choice 2
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();
You will probably need this permission too:
<uses-permission android:name="android.permission.WAKE_LOCK" />
UPDATE:
Try this method; android turns off the screen once the light level is low enough.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
The following is copied from SDK document.
If you want to keep screen on, I think SCREEN_BRIGHT_WAKE_LOCK is enough.
Flag Value CPU Screen Keyboard
PARTIAL_WAKE_LOCK On* Off Off
SCREEN_DIM_WAKE_LOCK On Dim Off
SCREEN_BRIGHT_WAKE_LOCK On Bright Off
FULL_WAKE_LOCK On Bright Bright
For me those methods didn't work. So I used other scenario (not trivial) to make my screen off.
Android has 2 flags that responsible to be awake:
Display --> Screen TimeOut
Application --> Development --> Stay awake while charging check box.
I used followed flow:
1st of all save your previous configuration, for example screen timeout was 1 min and Stay awake while charging checked.
After, I uncheck Stay awake while charging and set screen timeout to minimal time.
I register to broadcast receiver service to get event from android that screen turned off.
When I got event on screen off, I set previous configuration to default: screen timeout was 1 min and Stay awake while charging checked.
Unregister receiver
After 15 sec. device sleeps
Here is snippets of code:
BroadcastReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Catch Screen On/Off
* */
public class BroadcastReceiverScreenListener extends BroadcastReceiver{
private BroadCastListenerCallBackItf mBroadCastListenerCallBack = null;
public BroadcastReceiverScreenListener(
BroadCastListenerCallBackItf broadCastListenerCallBack) {
this.mBroadCastListenerCallBack = broadCastListenerCallBack;
}
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mBroadCastListenerCallBack.broadCastListenerCallBack__ScreenOff_onResponse();
}
}
}
Interface used as callback
public interface BroadCastListenerCallBackItf {
public void broadCastListenerCallBack__ScreenOff_onResponse();
}
2 methods from main class:
....
AndroidSynchronize mSync = new AndroidSynchronize();
....
public void turnScreenOff(int wait){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadCastListenerCallBackItf broadCastListenerCallBack = this;
BroadcastReceiver mReceiver = new BroadcastReceiverScreenListener(broadCastListenerCallBack);
m_context.registerReceiver(mReceiver, filter);
//set Development --> disable STAY_ON_WHILE_PLUGGED_IN
Settings.System.putInt(
m_context.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN,
0 );
// take current screen off time
int defTimeOut = Settings.System.getInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, 3000);
// set 15 sec
Settings.System.putInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, 15000);
// wait 200 sec till get response from BroadcastReceiver on Screen Off
mSync.doWait(wait*1000);
// set previous settings
Settings.System.putInt(m_context.getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
// switch back previous state
Settings.System.putInt(
m_context.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN,
BatteryManager.BATTERY_PLUGGED_USB);
m_context.unregisterReceiver(mReceiver);
}
public void broadCastListenerCallBack__ScreenOff_onResponse() {
mSync.doNotify();
}
....
AndroidSynchronize class
public class AndroidSynchronize {
public void doWait(long l){
synchronized(this){
try {
this.wait(l);
} catch(InterruptedException e) {
}
}
}
public void doNotify() {
synchronized(this) {
this.notify();
}
}
public void doWait() {
synchronized(this){
try {
this.wait();
} catch(InterruptedException e) {
}
}
}
}
[EDIT]
You need to register permission:
android.permission.WRITE_SETTINGS
Per this link, You can also turn the screen off like this:
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000);
1000 is in milliseconds which means 1 second, you can replace it with any value as desired.
Needed permission:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
try -
wakeLock.acquire(1000); // specify the time , it dims out and eventually turns off.

Categories

Resources