Solution to the problem that toast cannot be displayed normally in Android service

This example describes the solution to the problem that toast cannot be displayed normally in Android service. Share with you for your reference, as follows:

In the simple service exercise, toast is called in the oncreate, OnStart and ondestroy methods in the service as in the activity Maketext and call the OnStart and ondestroy methods of the service through two buttons in acitivy:

Demoservice code is as follows:

After running, the information in demoservice is not displayed.

At first, I thought the obtained context was incorrect. The service directly called getapplicationcontext() to get the service context. But from a closer look, toast can only be displayed after the context of the main UI. So I looked for it. In Google's description of toast, there is a sentence:

“A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service,it appears in front of the Activity currently in focus.” ( http://developer.Android.com/guide/topics/ui/notifiers/toasts.html )

According to this sentence, the toast created in the service will be focused and displayed in front of the activity UI. But why doesn't it work? Take another look at the maketext method.

Sure enough, it's still a context problem. Therefore, if you want the toast to work normally, you need to run it on the main thread of the activity. So how do you get the context of the main thread UI? You can run a custom thread on the main thread through the handler.

Take another look at toast SRC of show method:

In principle, Android is basically a message queue and a message loop. The main thread obtains and processes messages from the message queue. Handler is regarded as a tool class to insert messages into the message queue. So we refactor the original code:

The effect after operation is as follows:

Summary: when using toast in the Android framework, you need to add toast to the main thread to work normally.

For more Android related content, readers who are interested can view the special topics of this site: introduction and advanced tutorial of Android development, summary of Android view skills, summary of activity operation skills of Android programming, summary of skills of operating SQLite database for Android, summary of skills of operating JSON format data for Android, summary of operating skills of Android database Summary of Android file operation skills, summary of SD card operation methods for Android programming development, summary of Android resource operation skills and summary of Android control usage

I hope this article will help you in Android programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>