Inside onCreate of Application class, I set its instance to a static field, then show all application Toasts through this context. All works good except one thing, in some places a Toast can be shown before first activity can even appear but Toast never appears or sometimes just flashes. I think its because Activity not shown or drawn yet ? Or I'm missing something.
Edit:
More like showing toast from onCreate of Application class
Edit 2 :
public class TestApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Test from App", Toast.LENGTH_LONG).show();
}
}
If you want to show a Toast without the application even started manually by the user you can register a BroadcastReceiver which listens to the BOOT_COMPLETED system broadcast and then start a Service which will handle your Toasts.
You'll find many examples on how to do this.
To make a Toast before drawing your layout resources, just do this following.
//put this code before your setContentView(R.layout.your_layout);
Toast.makeText(yourclassName.this,"your text here",5000).show();
Well, consider one thing. If you want this toast to be shown before loading your activity and notify users some message. Then it might not be possible always. Because, The time Toast is shown with fraction of nano/mili seconds your layout is being loaded as-well.Moreover, scenario is totally different when you are on a real device and on a emulator.This might be the cause you got a flash of your Toast message. Just run it on a real device and you will see the differences.
Hope that helps
Related
I am developing an Android app.
In that, the existing flow is, there is a Toast Broadcasting Class which listened by MainActivity
Now we will call the emitter for the Toast from any activity and the toast will be shown from MainActivity (which is in onPaused state but alive , backstacked )
For example, We will call the emitter from WebViewActivity, the toast listener called from MainActivity will show the toast
Note that the Toast is an custom toast where the custom layout binded by toast.setView(layout)
Now my problem is ,
Starting from Android 11+,
If I call the toast emitter from MainActivity itself , that is when MainActivity is on top and Resumed , it's successfully shown
But, If I call it from Other Activites when MainActivity is passed, toast not showing
(I am using getApplicationContext to provide context for the toast)
I searched in the internet and found out that Custom Layout toast are deprecated after API LEVEL 30 and Toast cannot called from background
So is there is any way to show a Toast like alert, that run globally without attaching to any Activity Context showing above all activities ?
If I understand correct. I suggest you create a BaseActivity class and extend all your activities from it. And move your Toast logic from MainActivity to BaseActivity. Now you can use your Toast in your current active activity.
This is an odd one.
I was previously using:
android:keepScreenOn="true"
in my layout file to keep the screen on in an activity and this worked fine.
However I wanted to improve the so that the screen is only kept on when the web app is in a particular state. (The user should still be able to turn the screen off if they wish, I effectively just want to disable the timeout - which the above in the layout file achieves whenever the activity is active.)
To do this I have a JavaScript interface add to the WebView which casks the following two methods.
I have commented out the keepScreenOn setting in the layout.
#JavascriptInterface
public void keepScreenOn(){
Toast.makeText(mContext, "Keeping screen on", Toast.LENGTH_LONG).show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#JavascriptInterface
public void allowScreenOff(){
Toast.makeText(mContext, "Allowing screen off", Toast.LENGTH_LONG).show();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
Now the correct Toast is displayed, but the "keep screen on" action is reversed.
i.e. when I get the Toast saying the screen will be kept on it times out and switches of after a couple of minutes. BUT when I get the Toast saying that the screen will be allowed to turn off the screen actually stays on without ever timing out.
I don't understand how this can be.
OK, the plot thickens.
It seems it may not always be a reversal of the operation, but could be a random work/not working situation.
Also, looking in the log in Android Studio, I'm getting an error that says:
01-26 20:22:51.358 2182-5629/com.nooriginalthought.bluebadgeparking E/ViewRootImpl: com.nooriginalthought.bluebadgeparking.websiteViewActivity : Only the original thread that created a view hierarchy can touch its views.
when the method is called.
BUT it does work sometimes.
The methods shown above are within the websiteViewActivity class, but are not within the onCreate method. I'm afraid I don't know if this is relevant or how to ensure the addFlags and clearFlags are run in the correct thread if it is relevant.
[Edit: This question explains how to get things running on the UI thread and has got rid of the 'Only the original thread' error.]
And why does it sometimes work (I can't say if the error show up in the log when it works or not as I've only seen it working when testing away from my PC)?
The text "Only the original thread that created a view hierarchy can touch its views" means that you are executing this code from non-main thread, which is also called a UI Thread.
The WebView usually executes javascript in a background thread so that's why you get this error.
Try using "runOnUiThread()"
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "Keeping screen on", Toast.LENGTH_LONG).show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
private Window wind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//your code
wind = this.getWindow();
wind.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
wind.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
wind.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
wind.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
I am getting an error as Null pointer exception and unable to instantiate activity when I am creating a toast in activity constructor.I want to know the reason why toasts are working in onCreate method but not in activity constructor
The OS is responsible for constructing your Activity classes. This is because it needs to perform some setup, including providing the Activity a proper base Context. Without this, you cannot make Toasts.
In general, you should avoid doing anything in the constructor of an Activity (and you should definitely not be making instances of them yourself using new).
Usually a Toast appears as a feedback to user input (say a button click) or when some external event is registerd (say a network error happend or new incoming data is available).
However, to me it sounds as though you want to show a Toast right after opening your activity, is that correct? Then you should put it in the onCreate method of your activity. An example Toast is made like this
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG).show();
You might also consider putting this call in the onResume method. I recommend getting familiar with activity lifecycles.
Instead of using Toasts you might also want to check out Snackbars.
I use Toast dialogs a lot throughout my application. However, I have noticed that after switching activities, the dialog will continue to stay visible until its timer has run out.
Toast.makeText( getApplicationContext(), R.string.toast_need_bt, Toast.LENGTH_LONG ).show();
I use Toast.LENGTH_LONG because the message is long and if the user decides to read it, the longer time option is needed. However once the user has used the application once or twice they will not need to read the toast messages and they will quickly move from activity to activity. However, these toast dialogs stay on the screen even while switching from activity to activity.
Is there a way to end all Toast Dialogs if the current Activity is terminated?
Call cancel() on the toast object when finishing/leaving the activity
Here is a link to the documentation Toast
Toast.makeText returns a Toast object. Call cancel() on this object to cancel it.
Check this post for more answers on this topic How to cancel Toast
Even though there are a few answers already on how to use the .cancel() method, i would like to add a few options to this usecase:
1) Create in layout notifications Cyril Mottier's Article here
2) Display the toast only the first X times
3) Create a dialog with a "Show notifications" checkbox to allow the user to opt out.
I guess this is a question straight to Mark, but I can't for the life of me get a Toast notification to work from inside the doWakefulWork method of WakefulIntentService. It works from the onCreate, but I need to use some data I am getting through the intent within the toast message.
I've tried to instantiate the handler from within the OnCreate but this doesn't seem to do anything. I've tried everything I can think of. The Toast just doesn't seem to run on the main thread. Any help?
In general, WakefulIntentService is not designed for scenarios where a Toast would make any sense, since the user may or may not be around. Moreover, services should not be directly affecting the UI this way, since if the user is around the user may not appreciate your Toast in the middle of their game, their navigation, their movie, etc. I would rather you use something else (e.g., ordered broadcast to update a foreground activity or display a Notification if there is no such activity).
If you are really certain that you want to use a Toast from a service, your problem should have nothing to do with WakefulIntentService -- you would have the same problems with a regular IntentService. This SO question has some answers demonstrating the use of a Toast from a service's background thread using a Handler, which may help indicate where your Handler implementation is going wrong.
private boolean showToast = false;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (showToast) {
Toast.makeText(this,"YourText",Toast.LENGTH_LONG).show();
showToast = false;
}
}
Just set showToast = true; from anywhere to showing you toast notification.