English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Questo articolo illustra il metodo per risolvere il problema di Toast non visualizzato correttamente nell'Android Service. Condivido con tutti per riferimento, come segue:
Durante l'esercitazione di Service, nei metodi OnCreate, OnStart e OnDestroy del Service, sono stati chiamati come nei metodi uguali dell'Activity Toast.makeText, e nella Activity sono stati chiamati i metodi onStart e onDestroy del servizio tramite due pulsanti:
Il codice del DemoService è il seguente:
@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(); }
Dopo aver eseguito, le informazioni nel DemoService non sono state visualizzate.
All'inizio si credeva che il Context ottenuto non fosse corretto, chiamando direttamente getApplicationContext() nel Service si ottiene il Context del Service, ma dopo aver analizzato attentamente, Toast dovrebbe ottenere il Context dell'UI principale per poter essere visualizzato, quindi ho cercato un po', e nella descrizione di Toast di Google, c'è una frase:
"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.
Indeed, it is a problem of Context, so in order for the toast to work normally, it needs to be run on the main thread of the Activity. So how to get the Context of the main thread UI? You can run a custom thread on the main thread through a Handler.
Let's take a look at the src of Toast.show method:
public void show() { ... service.enqueueToast(pkg, tn, mDuration); //Insert the toast into a message queue ... }
In terms of principle, in Android it 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(); } }); }
L'effetto dopo l'esecuzione è il seguente:
Sommario:Per utilizzare Toast nel Framework di Android, è necessario aggiungere Toast alla thread principale per funzionare correttamente.
I lettori interessati a contenuti relativi a Android possono consultare le sezioni speciali di questo sito: 'Tutorial di avvio e avanzamento dello sviluppo Android', 'Riassunto delle tecniche di View Android', 'Riassunto delle tecniche di gestione activity in Android', 'Riassunto delle tecniche di gestione del database SQLite in Android', 'Riassunto delle tecniche di gestione dei dati in formato JSON in Android', 'Riassunto delle tecniche di gestione del database in Android', 'Riassunto delle tecniche di gestione dei file in Android', 'Riassunto delle tecniche di gestione della scheda SD in Android', 'Riassunto delle tecniche di gestione delle risorse in Android' e 'Riassunto dell'uso dei controlli Android'.
Spero che questo articolo possa essere utile per la progettazione di applicazioni Android.
Dichiarazione: il contenuto di questo articolo è stato tratto da Internet, il copyright spetta ai rispettivi proprietari, il contenuto è stato contribuito e caricato autonomamente dagli utenti di Internet, questo sito non detiene il diritto di proprietà, non è stato editato manualmente e non assume responsabilità legali correlate. Se trovi contenuti sospetti di violazione del copyright, ti preghiamo di inviare una email a notice#oldtoolbag.com (al momento dell'invio dell'email, sostituisci # con @) per segnalare, fornendo prove pertinenti. Una volta verificata, questo sito rimuoverà immediatamente il contenuto sospetto di violazione del copyright.