views:

51

answers:

1

Hi,

Imagine I have the following code that runs as a background processor for an android application:

public class Background extends Service 
{
    public void popup (String message, int duration)
    {
        Toast.makeText(this, message, duration).show();
    }

    class BackgroundChecker extends TimerTask 
    {
        public void run()
        {
            popup("Message!", Toast.LENGTH_LONG); // here
        }
    }
}

When it reaches the popup message i.e. // here, Android tells me to force quit. I know that the problem is with context i.e. this, but I don't know why because I have extended Service in that class which Android API told me to. Can you help me figure out why this is happening and how to fix it? By the way, instead of this I used getApplicationContext() as well but it still crashes =(.

Thank you.

A: 

I havent tried this, but how about having your service tell an activity to do a toast, since a Service is a background activity it seems like its context wouldnt work to do a toast.

Something else you could try is to extend the Application class, and have a toast generator there, and then from your service call.

ApplicationExtender variableName = (ApplicationExtender) Background.this.getApplication();              
variableName.toast("message");

Your ApplicationExtender:

public class ApplicationExtender extends Application {

    public void toast(String message){
    Toast.makeText(super.getApplicationContext(),message,Toast.LENGTH_LONG).show();
    }

}

You need to add your extending class to your manifest for it to work.

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ApplicationExtender">

I cant garantee this will work, I havent tried it.

blindstuff
I'm sorry, what do you mean by Application class above? Do you mean Background class
androidNoob
Nope sorry, I tried it but it still crashes. Any other suggestions?
androidNoob
I would need to see your logCat to give you any more feedback.
blindstuff
Hey sorry to reply back so late. I decided not to use the toast message after all. It was becoming tedious and I think toast is meant to be used from within a UI. So, I went with the status bar Notification which works perfectly from within a background service. Thanks for all you help. I really appreciate it!
androidNoob