How can show a custom Toast from a Service?

时间:2016-08-31 18:29:21

标签: java android android-activity service toast

I have worked some time to get information how to show a custom Toast. This is my code

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE );
    View layout = inflater.inflate(R.layout.custom_toast, null);

    ImageView image = (ImageView) layout.findViewById(R.id.customtoastImageView1);
    image.setImageResource(R.drawable.stats);
    image.setColorFilter(More.getMore(getApplicationContext()).getColor(R.color.on));
    TextView text = (TextView) layout.findViewById(R.id.customtoastTextView1);
    text.setText("App opened " + getSharedPreferences(Prefs.PREFERENCE_APPS_COUNT, MODE_PRIVATE).getString(packagename, "0") + " times.");

    final Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.TOP, 0, 50);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();

This code works in an Activity. But when I use it from my Service the App crashes. So my question is how to show a custom Toast from a Service. Thanks.

EDIT

A simple Toast works, the problem is the custom Toast.

0 个答案:

没有答案