#Override
public void run() {
//Create thread that can alter the UI
AlarmPage.this.runOnUiThread(new Runnable() {
public void run() {
cal = Calendar.getInstance();
//See if current time matches set alarm time
if((cal.get(Calendar.HOUR_OF_DAY) == alarmTime.getCurrentHour())
&& (cal.get(Calendar.MINUTE) == alarmTime.getCurrentMinute())){
//If the sound is playing, stop it and rewind
if(sound.isPlaying()){
ShowDialog();
alarmTimer.cancel();
alarmTask.cancel();
alarmTask = new PlaySoundTask();
alarmTimer = new Timer();
alarmTimer.schedule(alarmTask, sound.getDuration(), sound.getDuration());
}
sound.start();
}
}
});
}
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT);
}
});
alertDialog.show();
}
I am making a simple alarm clock app that notifies the user. I want to make a alert box that gives the user the option to turn off the alarm when it goes off. I was able to make the alert box, but it only appears in the app not outside of the app. I understand the app has to be in the background running. If I need to show more code or be more specific, just ask please.
Add a line as:
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
// line you have to add
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
check now.
Do not accept answers if they don't address your question, it is misleading.
The accepted answer is not correct, as it will never work outside your application.
Reason:
It requires an activity context not application context.
If you provide application context, your app will crash with IllegalArgumentException- you need to use Theme.AppCompat or their decendents...
If you need functionality as actually stated in the question you have to have a separate activity themed as a Dialog like here
or you can add a custom view to your window using window manager and making it system level alert like here.
Do this create an Activity without ContentView or a View associated with it and call your alertDialog method in your onCreate also remember to set the background of the Activity to Transparent using ColourDrawable
And that activity will look like a dialog or will suit your preference, you can also fall back to Themes so you can set an Activity as Dialog and treat it like Dialog also use DialogFragment
Related
I have this code to take you to other applications from my page.
Button more_apps = (Button)findViewById(R.id.more_apps);
more_apps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent more_apps = new Intent();
more_apps.setAction(Intent.ACTION_VIEW);
more_apps.addCategory(Intent.CATEGORY_BROWSABLE);
more_apps.setData(Uri.parse("https://play.google.com/store/apps/dev?id=****"));
startActivity(more_apps);
}
});
No problem other than that sometimes google play rejects the app and sends me a picture indicating that the 'more apps' button is promoting other apps. ..Bla bla bla
So I had an idea: when you click on the button, a confirmation message appears to go “yes” or “no”, and if you press “yes” it directs you to the link, and pressing “no” remains in the application.
How can this be achieved please
Probably the simplest way to show a dialog is to build using the AlertDialog.Builder().
You can use the following method from some random Util Class and just pass the arguments:
public static AlertDialog createAlert(String message, String positiveButtonText, DialogInterface.OnClickListener positiveListener, String negativeButtonText, DialogInterface.OnClickListener negativeListener, Context context, boolean isCancelable) {
return new AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(positiveButtonText, positiveListener)
.setNegativeButton(negativeButtonText, negativeListener)
.setCancelable(isCancelable)
.create();
}
And you use it like this:
AlertDialog goToPlayStoreDialog = RandomUtilClass.createAlert(
"Do you want to see more of my apps?",
"Yes", positiveListener,
"No", negativeListener,
context, false);
goToPlayStoreDialog.show();
And here is how a listener is implemented:
DialogInterface.OnClickListener positiveListener = (dialog, which) -> {
**Start intent here**
};
As for the negative listener, simply call dialog.dismiss();
Note that you should implement the listeners before creating the dialog :)
Initially in my app I am creating an AlertDialog which has three buttons, in which the middle button opens up another AlertDialog. The problem is that when the second AlertDialog closes after a button is pressed, the first one closes with it. I think both AlertDialogs get closed after I press a button on the second AlertDialog.
What I want is for the first AlertDialog to open another AlertDialog that has its own buttons, and when second AlertDialog presses a button, it only closes itself and goes back to the first one. Is there any way to achieve this?
Here is the code for the button used to open the AlertDialog:
final ImageButton fabgroup = (ImageButton) findViewById(R.id.groupButton);
Here's the code for a button that opens an AlertDialog that contains another button that opens another AlertDialog using the middle button (create button) on itself, but closes them both when a button on the second one is pressed (either the yes or no button, which is not what I want as I only want the second one to close itself and go back to the first AlertDialog, and yea this sounds pretty confusing in theory so I can try to clarify if needed):
fabgroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(CreateNote.this);
helpBuilder.setTitle("Select a group");
helpBuilder.setMessage("Add to group?");
final TextView input = new TextView(mainactiv.this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Toast.makeText(CreateNote.this, "Page has been added to group", Toast.LENGTH_SHORT).show();
}
});
helpBuilder.setNeutralButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//open another alertbox
AlertDialog.Builder helpBuilder2 = new AlertDialog.Builder(CreateNote.this);
helpBuilder2.setTitle("Assign a new group");
helpBuilder2.setMessage("Create group?");
final EditText input = new EditText(CreateNote.this);
input.setSingleLine();
input.setText("");
helpBuilder2.setView(input);
helpBuilder2.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Create Group
Toast.makeText(CreateNote.this, "Group has been created", Toast.LENGTH_SHORT).show();
}
});
helpBuilder2.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog2 = helpBuilder2.create();
helpDialog2.show();
}
});
helpBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
});
Help would be greatly appreciated.
I eventually managed to solve this problem by creating two separate functions to generate each dialog box, and when one closes it calls the function to create the other one, kinda like recycling (or maybe closer to looping functions). Although, I'm not entirely sure how performance heavy this is, but it seems to do the job without any issues from what I'm testing. If anyone would like to chime in on how this could be an issue, then I'm open to hearing what others have to say about the negative points of using alert dialog boxes this way.
You can show an activity as dialog. Put this in your manifest file.
<activity android:theme="#android:style/Theme.Dialog" android:excludeFromRecents="true"/>
From this answer: Android Activity as a dialog
I need to make a math quiz. Here is workflow:
On button click(Start) i need to show a question e.g. 5+5, which stays on screen for 2 seconds after which a dialog i shown asking for result of previous operation. And i need to repeat that for e.g. 5 times. At the end I need to show to user number of correct answers.
I have Java experience but I'm new to Android. I have read various articles and examples regarding Android threading but haven't found solution to this workflow.
As far as I know I cannot block or pause main/UI thread, but the problem is that i should repeat questions for e.g. 5 times and after each one(after 2 sec.) I should pause activity to show Dialog and then go back to showing another question.
Thanks in advance!
EDIT:
Here is my code for now. The number is shown on screen and after 2 seconds alert dialog is shown asking to enter that number. But the problem is that the application doesn't wait for user input but continues to show new random number an opens new alert dialog every 2 seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
tv = (TextView) findViewById(R.id.questionText);
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.setText(String.valueOf(rand.nextInt(50) + 1));
createDialog();
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(r, 2000);
}
protected void createDialog() {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.activity_answer_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
result.setText(userInput.getText());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
PS. Also I tried to create separate Activity for dialog and added this line to Manifest:
android:theme="#android:style/Theme.Dialog"
but the same thing happens.
You use event driven programming and timers. To show the dialog after 2 seconds, the easiest way is to post a runnable to a handler using postDelayed, which will call your runnable in N milliseconds. Then display the dialog box.
You don't need to pause the activity to show the dialog box, just show it. Any code that you want to run after the dialog is finished with should be put in the handler for the dialog's ok button. In other words, your code is called in response to the event of a button being pressed.
Following... this link ..How to set image as wall paper in viewpager app?. I am able to set wallpaper directly located in my drawable folder. However, i want to give user a chance to set wallpaper by displaying pop up dialogue box which should be displayed. When user clicks on images for 3-5 sec.
I am kind of new to android programming.. So, please help..
android framework already supporting class "alertDialogue.builder". you can set message whatever you wanna show in addition to dialogue buttons, title etc.
http://developer.android.com/reference/android/app/AlertDialog.Builder.html
5sec is too long to stay in one fingerpoint. in onsimplegesturedetector class, there is already "long press" detector
http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html
you can set your own ontouchListener that implements onTouchListener that has gesture detector, detects long press and can show dialogue .
there can be better way but I'm using this logic in my project so you can reference and fix it if you find better way
findViewById("your wall paper image id").onTouchListener(new MyOnTouchListener());
class MyOnTouchListener implements onTouchListener{
GestureDetector gd = new GestureDetector(new SimpleOnGestureListener(){
#Override
public void onLongPress(MotionEvent e) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Your Title");
alertDialogBuilder
.setMessage("click yes to set wallpaper!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//setting wallpaper
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
I need a popup dialog to be shown when i get a message from different thread but the dialog should be not dependent on Activity i.e, it should display the dialog wherever the screen focus is.
Can it be done? Because the dialog is handled per Activity, I thought of using a service but again it would be one more thread added and I want to avoid that.
Any other options available?
If you're trying to ask how to show a dialog when your activity is not the focused activity on the user's phone then try using Notifications instead. Popping up a dialog over a different application interrupts the user when they may be doing something else. From the Android UI guidelines:
Use the notification system — don't
use dialog boxes in place of
notifications
If your background service needs to
notify a user, use the standard
notification system — don't use a
dialog or toast to notify them. A
dialog or toast would immediately take
focus and interrupt the user, taking
focus away from what they were doing:
the user could be in the middle of
typing text the moment the dialog
appears and could accidentally act on
the dialog. Users are used to dealing
with notifications and can pull down
the notification shade at their
convenience to respond to your
message.
A guide to create notifications is here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Alternative solution :
AlertDialog dialog;
//add this to your code
dialog = builder.create();
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mInputView.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//end addons
alert.show();
if I understand you correctly you could use a base class for all of your activities
public abstract class BaseActivity extends Activity{
protected static BaseActivity current_context = null;
#override
protected void onPause(){
current_context = null;
super.onPause();
}
#override
protected void onResume(){
current_context = this;
super.onResume();
}
public static void showDialog(/*your parameters*/){
//show nothing, if no activity has focus
if(current_context == null)return;
current_context.runOnUiThread(new Runnable() {
#override
public void run(){
AlertDialog.Builder builder =
new AlertDialog.Builder(current_context);
//your dialog initialization
builder.show();
}
});
}
}
in your thread show your dialog with BaseActivity.showDialog(..) But this approach doesn't work if you want to show your dialog on top of any activity of the target device.