English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Solution to the problem of Toast not displaying normally in Android Service

This article describes the solution to the problem of Toast not displaying normally in Android Service. Share it with everyone for reference, as follows:

When practicing with a simple Service, Toast.makeText was called in the OnCreate, OnStart, and OnDestroy methods of the Service, just like in the Activity. In the Activity, two buttons were used to call the onStart and onDestroy methods of the service:

The code for DemoService is as follows:

@Override
public void onCreate()
{
    super.onCreate();
    Toast.makeText(getApplicationContext(), "Service is created!", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    Toast.makeText(getApplicationContext(), "Service is on!", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy(){
    super.onDestroy();
    Toast.makeText(getApplicationContext(), "Service is off!", Toast.LENGTH_LONG).show();
}

After running, the information in DemoService did not display at all.

Initially, it was thought that the obtained Context was incorrect, as getApplicationContext() directly called in the Service returns the Service's Context. However, upon closer examination, Toast should receive the main UI's Context in order to display. So, I searched a bit, and 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 displayed in front of the UI of the Activity currently in focus. But why does it not work as expected? Let's take a look at the makeText method again.

Sure enough, it's a Context issue. Therefore, in order for the toast to work normally, it needs to be run on the main thread of the Activity. So how can we get the Context of the main thread UI? We can run a custom thread on the main thread through a Handler.

Let's take a look at the src of Toast.show method again:

public void show() {
    ...
    service.enqueueToast(pkg, tn, mDuration);  //Insert this toast into a message queue
    ...
}

In principle, Android is roughly a message queue and message loop, where the main thread retrieves messages from the message queue and processes them. The Handler is considered a utility class, used to insert messages into the message queue. Therefore, we refactor the original code:

@Override
public void onCreate()
{
    super.onCreate();
    handler=new Handler(Looper.getMainLooper());
    handler.post(new Runnable(){
      public void run(){
        Toast.makeText(getApplicationContext(), "Service is created!", Toast.LENGTH_LONG).show();
      }
    });
}
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    handler=new Handler(Looper.getMainLooper());
    handler.post(new Runnable(){
      public void run(){
        Toast.makeText(getApplicationContext(), "Service is on!", Toast.LENGTH_LONG).show();
      }
    });
}
@Override
public void onDestroy(){
    super.onDestroy();
    handler=new Handler(Looper.getMainLooper());
    handler.post(new Runnable(){
      public void run(){
        Toast.makeText(getApplicationContext(), "Service is off!", Toast.LENGTH_LONG).show();
      }
    });
}

The effect after running is as follows:

Summary:In Android's Framework, you need to add Toast to the main thread to work normally.

Readers who are interested in more about Android-related content can check out the special topics on this site: 'Android Development入门与进阶教程', 'Android视图View技巧总结', 'Android编程之activity操作技巧总结', 'Android操作SQLite数据库技巧总结', 'Android操作json格式数据技巧总结', 'Android数据库操作技巧总结', 'Android文件操作技巧汇总', 'Android编程开发之SD卡操作方法汇总', 'Android资源操作技巧汇总' and 'Android控件用法总结'

I hope the description in this article will be helpful to everyone in Android program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report violations by sending an email to codebox.com (replace # with @ when sending emails), and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.

You May Also Like