I have an IntentService that downloads some files. The problem is that I create a Toast inside the IntentServi开发者_JS百科ce like this
Toast.makeText(getApplicationContext(), "some message", Toast.LENGTH_SHORT).show();
The Toast will never disappear event if I exit the app. The only way to destroy it is to kill the process.
What am I doing wrong?
The problem is that IntentService
is not running on the main application thread. you need to obtain a Handler
for the main thread (in onCreate()
) and post the Toast
to it as a Runnable
.
the following code should do the trick:
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
@Override
protected void onHandleIntent(Intent intent) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyIntentService.this, "Hello Toast!", Toast.LENGTH_LONG).show();
}
});
}
This works for me:
public void ShowToastInIntentService(final String sText) {
final Context MyContext = this;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast toast1 = Toast.makeText(MyContext, sText, Toast.LENGTH_LONG);
toast1.show();
}
});
};
IntentService will create a thread to handle the new intent, and terminated it immediately once the task has done. So, the Toast will be out of controlled by a dead thread.
You should see some exceptions in the console when the toast showing on the screen.
For people developing in Xamarin studio, this is how its done there:
Handler handler = new Handler ();
handler.Post (() => {
Toast.MakeText (_Context, "Your text here.", ToastLength.Short).Show ();
});
To show a toast when the user is in one of the application activity.
Just need a reference of the current activity, and call it with this sample code:
public void showToast(final String msg) {
final Activity a = currentActivity;
if (a != null ) {
a.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(a, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
There is a lot of options to get the current activity, check this question: How to get current foreground activity context in android?
But I use this approach:
The application must have:
private Activity currentActivity = null;
public Activity getCurrentActivity() {
return currentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity) {
this.currentActivity = mCurrentActivity;
}
Each activity must have:
@Override
protected void onResume() {
super.onResume();
((MyApplication) getApplication()).setCurrentActivity(this);
}
@Override
protected void onPause() {
super.onPause();
((MyApplication) getApplication()).setCurrentActivity(null);
}
You shouldn't create Toast
s from a Service
. You should use a Notification
instead.
精彩评论