简体   繁体   中英

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!

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.

I know I'm 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.

I'm doing this kind of thing using Application class. You need to declare your own - eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM