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.
Related
I have a dialog activity which sets up an alert dialog every time the alarm goes off. Now this alert dialog can be infront of any activity. As it gets called by the alarm manager when the alarm is supposed to go off.
The problem is that if this alert dialog comes infront of the main activity which holds the list of upcoming alarms then when I "dismiss" the alarm, that alarm should get removed from the list( which does get deleted) but after the alert dialog disappears the main activity doesn't get updated unless I resume the activity or go to next activity and then back to main activity.
I tried calling the main activity inside the onDismiss method of the dialog like this:
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
((MainActivity) context).customAdapter.notifyDataSetChanged();
}
});
However I get an exception that my DialogActivity's context can't get converted into main activity's context. How can I solve this?
Here's my Dialog Activity class
public class DialogActivity extends AppCompatActivity {
AlarmManager alarmManager;
PendingIntent pendingIntent;
Intent startSetAlarm;
Intent i;
Intent intent;
String alarmStatus;
int alarmID;
String alarmName;
String alarmTime;
String alarmAMPM;
String alarmSound;
String snoozingType;
Context context;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeListener mShakeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
........
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Alarm Clock")
.setMessage("What to do with " + alarmName + ": " + alarmTime + " " + alarmAMPM +"?")
.setCancelable(false)
.setPositiveButton("Dismiss", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
alarmManager.cancel(pendingIntent);
i.putExtra("Status","Alarm Off");
i.putExtra("calledBefore",true);
i.putExtra("Alarm ID", alarmID);
i.putExtra("Alarm Name", alarmName);
i.putExtra("Alarm Time", alarmTime);
i.putExtra("Alarm AMPM", alarmAMPM);
i.putExtra("Alarm Sound", alarmSound);
i.putExtra("Snooze Type", snoozingType);
sendBroadcast(i);
dialog.dismiss();
finish();
//startActivity(startSetAlarm);
}
})
.setNegativeButton("Snooze", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
alarmManager.cancel(pendingIntent);
i.putExtra("Status","Alarm Off");
i.putExtra("calledBefore",true);
i.putExtra("Alarm ID", alarmID);
i.putExtra("Alarm Name", alarmName);
i.putExtra("Alarm Time", alarmTime);
i.putExtra("Alarm AMPM", alarmAMPM);
i.putExtra("Alarm Sound", alarmSound);
i.putExtra("Snooze Type", snoozingType);
sendBroadcast(i);
Snooze();
dialog.dismiss();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
And then I call the onDismiss method which I showed earlier. I also tried making a constructor of DialogActivity and initializing dialogactivity's object in main, to pass main's context into it however I get the error that "Dialog activity doesn't have a constructor with no parameters" If I make a default constructor, I still get an exception and it doesn't work.
UPDATE
I figured it out. I had to retrieve my list stored in shared preferences in order to get the updated one. The updated list was only getting called in onCreate not in onResume.
However I have another problem now. Which is still related to the same activity life cycle dilemma. If my application is closed (and is not in opened apps list) and I receive the dialog notification, If I dismiss the alarm, it turns off and the dialog goes away. However I can see my app now in the recent list. And when I open my app from there, my dialog activity is active and it just keeps on showing the dialog and doesn't let me enter the app. Unless I go to the app drawer and open the app from there. Here is a screenshot of what I mean.
Dialog Problem
You must use BroadcastReceiver or EventBus library . Your activity before create not to be refresh you ListView .
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 want to show an alert dialog when booting of device is completed. There are no problems with the broadcast receiver, it works fine. But when boot is completed, there is no open activity, hence I get NullPointerException here. How can I show a dialog box in this situation? This is the code I use to show the dialog:
public class RestartReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
AlertDialog alertHelp;
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
TextView m_timetext = new TextView(context );
m_timetext.setText("hello");
// m_timetext.setTextColor(getResources().getColor(R.color.dark_green));
LinearLayout linearLayout = new LinearLayout(context );
linearLayout.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
linearLayout.setOrientation(1);
linearLayout.addView(m_timetext);
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}});
alertHelp = dialog.create();
alertHelp.setView(linearLayout);
alertHelp.show();
Log.d("In","Switched On");
}
}
Please help me. Thanks in advance.
Here is a post on how to do it. You can get the source code from here.
Your code doesn't work because you can't show dialog directly from your broadcast receiver. You have to use an Activity. Also, in order to receive ACTION_BOOT_COMPLETED your activity must be first explicitly started by user or by another application (google application stopped state for more information).
Basically, to achieve the required functionality, you need to do:
Create transparent activity that shows dialog.
Create BroadcastReceiver that receives ACTION_BOOT_COMPLETED and starts your activity.
Register your broadcast receiver in the manifest and acquire a proper permission.
Also, this question provides more information on how to create a transparent activity.
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.
I have used a timer method in an Activity class. In that method I have an intent from Activity class to a BroadcastReceiver class.
This BroadcastReceiver class will call on every 15 minutes at background by using AlarmManager.
When I call the BroadcastReceiver class I would like to raise an AlertDialog.
public void timerMethod(){
Intent intent = new Intent(Activity.this,
BroadcastReceiverClass.class
);
PendingIntent sender = PendingIntent.getBroadcast(
QualityCallActivity.this,0, intent, 0
);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 60*1000, sender);
}
BroadcastReceiverClass.java
public void onReceive(Context context, Intent intent)
{
dialogMethod();
}
How can I raise an AlertDialog from BroadcastReceiver class from a background process?
If your activity is running when the BroadcastReceiver gets the intent you should be able to use runOnUiThread to run a method that creates an AlertDialog, e.g.:
public void onReceive(Context context, Intent intent)
{
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder d = new AlertDialog.Builder(MyActivity.this);
b.setMessage("This is a dialog from within a BroadcastReceiver");
b.create().show();
}
});
}
This works if you make your BroadcastReceiver an inner class to your Activity.
In short: It is not possible.
Only Activity's can create/show dialogs. In fact, this has been asked more then once:
AlertDialog in BroadcastReceiver
How can I display a dialog from an Android broadcast receiver?
Also, this would give a very bad user-experience:
If the user is not in your application (let's say he's playing a
Game) and your Dialog pops up every 15 minutes, this will be very
annoying for him.
If the user is in your application, there are several other (better
suited) ways to notify him that something has been executed.
Better suited ways
In fact, you can create/show a Toast from an BroadcastReceiver. This Toast will also bee shown when the user is not "in your application".
Also, you can send a Notification (shown in the Notification-Bar at the top of your screen) from a BroadcastReceiver. A tutorial on how to do this (it does not differ from how you do it in an Activity, except that you use the passed Context-Object from the onReceive-method).
The Notification will also be shown when the user is not "in your application" and is IMO the best solution to this problem.
1) In Activity:
public static Context ctx;
onCreate {
ctx = this;
}
public void showAlertDialog(Context context, String title, String message) {
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
2) In BroadcastReceiver.onReceive:
YourActivity ac= new YourActivity ();
ac.showAlertDialog(YourActivity.ctx, "test", "test");