John Leehey
John Leehey

Reputation: 22240

How to launch a background activity from a widget?

I have an android widget which has a very simple function. The widget simply launches an activity when pressed, runs through the activity, pops a toast, and closes the activity.

The annoying thing is that when the widget is pressed on the home screen, the screen flickers as it opens and closes the activity. Is there any way to launch the activity from the background, to avoid this flicker? I'm kind of looking to do something similar to the ATK widget, which simply pops up a toast after closing all the background processes.

If it's possible to just run a single function in place of a PendingIntent, that would definitely work as well. Thanks!

Upvotes: 0

Views: 1069

Answers (3)

balta
balta

Reputation: 11

I know I'm very late, but I was having a similar problem and I didn't want to use a service.

If your activity is very quick, it is enough to modify your manifest and insert this into the activity your widget will be launching,

android:theme="@android:style/Theme.Translucent.NoTitleBar"

This way your activity will be transparent thus no flickering will be seen and, being it very quick it won't get in the way.

Please note that this may only be used if your activity is fast, otherwise it will result in a frozen effect.

Upvotes: 1

John Leehey
John Leehey

Reputation: 22240

I eventually did this by implementing a service instead of an activity. The service runs in the background and then stops itself once it has finished. The PendingIntent simply launches the service, using the getService() method of PendingIntent.

Upvotes: 1

Barmaley
Barmaley

Reputation: 16363

I'm doing this kind of thing using Application class. You need to declare your own - e.g. MyApplication class (need to be declared in Android manifest) and during creation MyApplication just launch separate Thread:

public class MyApplication()
{

    // only lazy initializations here!
    public MyApplication()
    {
        super();
    }


    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "Starting MyApplication"+this.toString());
        Thread myThread=new MyThread();
        myThread.start();
    }
}

So in the end you will have "background" application which doesn't contain any activities. Application will be alive while your thread is alive. From those thread you can start whatever you want - for instance popup window, toast or any activity - depending on what you want.

Upvotes: 0

Related Questions