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.
Related
I am developing a app for Android. I have a method called ringtone that is called when certain conditions are met. I wanted to create a lound sound and create a dialog box to dismiss the sound.
My code:
public void ringtone() {
AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_RING, 10, AudioManager.FLAG_SHOW_UI);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
final Ringtone r= RingtoneManager.getRingtone(getApplicationContext(), notification);
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext()).create();
alertDialog.setTitle("We Detected You Were Asleep");
alertDialog.setMessage("WAKE UP!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "I am Awake", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
r.stop();
}
});
r.play();
alertDialog.show();
}
When I run my app the ringtone volume changes but the ringtone doesn't play. However when I comment out the dialog box builder the ringtone rings. So my conclusion is that there is something wrong within the dialog box builder that isnt allowing the code to continue.
I have wondered that myself a few times: My dialog was shown on an activity, that was currently off screen.
Solution: You need to create the builder with the context of the activity, the dialog should be displayed with.
I have created the builder with the context of another activity (my shared main activity) and that was wrong.
Now in your case, you might have to create and show a translucent activity, where you display your dialog on. Creating a translucent activity is just a few settings in the manifest file.
I am using Notification in MainActivity.class and i have checkbox in another Settings.class from where i want to enable or disable vibration on notification. Everything working fine but when i uncheck the checkbox vibrate still remain until refresh or restart the app. I don't want to refresh the activity or restart the app.
In main class :
#Override
public void onResume() {
super.onResume();
if(settingsAct.checkStatus1==1){
notify.defaults |= notify.DEFAULT_VIBRATE;
}
}
In Settings class :
if(mCheckVibrate.isChecked()){
checkStatus1 = 1;
}else{
checkStatus1 = 0 ;
}
Finally i have solved my problem i have changed from default notification vibration to following:
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(300);
For disabling vibration i have used :
vibrator.cancel();
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"/>
So my app has a timer that displays in the main activity as it is counting down. I want an alarm to play when the timer is done, so I schedule an intent that sounds the alarm using AlarmManager and a class to extend BroadcastReceiver.
Everything works fine until the alarm goes off. I traced the crash to the line where I call show() on my AlertDialog. I feel like it has something to do with the application context and the code not being in MainActivity or something, but I can't seem to find anything with a similar configuration and the same crash source.
Here is the alert dialog code
public class SoundAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
...///Play sound code is here and works
final CharSequence [] options = {"OK"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Beer is done!");
builder.setCancelable(false);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(which == 0) {
mp.stop();
mp.release();
}
}
});
AlertDialog alert = builder.create();
alert.show();
... //other stuff
Here is the code that schedules with the AlarmManager which is found in MainActivity.java:
//Schedule the alarm
Intent alarmIntent = new Intent(MainActivity.this, SoundAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Calendar fireTime = Calendar.getInstance();
fireTime.setTimeInMillis(System.currentTimeMillis());
fireTime.add(Calendar.MILLISECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, fireTime.getTimeInMillis(), pendingIntent);
Also, as an aside, changing the MainActivity.this to getApplicationContext() for the pending intent does not fix the crash. Saw a lot of people suggesting using one or the other, but my crash persists no matter which one I use.
I feel like it has something to do with the application context and the code not being in MainActivity or something,
Yes, you need an Activity to show a Dialog.
What you can do is build a separate Activity with the layout you want and start it from the Receiver. You can add the following code to the <activity> tag of your manifest.xml to make it appear as a Dialog.
android:theme="#android:style/Theme.Dialog"
From the Docs
Note: Activities provide a facility to manage the creation, saving and restoring of dialogs.
I have a service that turn on my app sometimes, the main activity prompt Dialog message to user sometimes,
after the user answer YES\NO I call to finish() to close the app.
my problem is when the message is shown, user answers it and app was call to finish() and when you look in the recent history you played before (in samsung for example you press long on home button) you will see my app along with other apps user started.
when you push it to open it again the Dialog show again..
How to show the activity when launched from recent app without showing the Dialog
public void dialog_1(){
myDialogViewN = new MyDialogViewNegativeTime(MainActivity.this);
// Setting vibrator
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern= {100, 1000};
vibrator.vibrate( pattern,0 );
// Setting 2 Dialog Listeners
myDialogViewN.setOnDialogListener(new DialogListener() {
#Override
public void onNegativeClick()
{
// Stopping Vibraror
if (vibrator.hasVibrator()){
vibrator.cancel();
vibrator = null;
}
initialize_DialogToUser(); /// ??
SendDataToService(3); //doesn't want reminder
myDialogViewN.dismissDialog();
waitForDialogAnswer=false;
finish();
}
#Override
public void onPositiveClick()
{
// Stopping Vibrator
if (vibrator.hasVibrator()){
vibrator.cancel();
vibrator = null;
}
initialize_DialogToUser();
SendDataToService(1); //remind!
myDialogViewN.dismissDialog();
squre.setImageResource(R.drawable.triangle_red2);
waitForDialogAnswer=false;
finish();
} });
myDialogViewN.show();
}
#Override
public void onDestroy()
{
super.onDestroy();
// close/stop running application on background
int id= android.os.Process.myPid();
android.os.Process.killProcess(id);
}
finally i find solution,
the problem was when you open the app from history - the last intent that comes from service to your activity stay there and not goes, in contrary for openning the app by click it's own icon. (different openning ways).
my solution:
send 2 intent's from service to activity,
the first - with what you really need.
the second - after you receive your answer in the service. in the second you will not put any data! it is a mere intent that comes to change the "stuck" intent in history-app open way.
maby it is stupid, but it's the only solution i found :)