如何检测特定Android应用程序何时进入后台?

时间:2015-10-29 13:12:24

标签: android

我试图编写一个应用程序,当另一个特定应用程序转到后台时,该应用程序将启动或显示通知或弹出窗口。 例如:

  • 用户启动应用A
  • 用户使用应用A
  • 用户将app A置于后台,方法是按主页按钮或后退按钮或启动另一个应用
  • 我的应用检测到并自行启动或显示弹出窗口或其他

有没有办法做到这一点,如果有,没有杀死电池?

3 个答案:

答案 0 :(得分:1)

在您的应用程序 A 中,将以下代码放在一个类中:

package it.mysite;

@SpringBootApplication
@EnableTransactionManagement
public class MailSenderApplication {

    @Autowired MySendService mySendService;

    public static void main(String[] args){
        ConfigurableApplicationContext context = SpringApplication.run(MailSenderApplication.class, args);

        System.out.println("*****");
        for (String name : context.getBeanDefinitionNames()) {
            System.out.println(name);
        }
        System.out.println("*****");
        new MailSenderApplication().boot();
    }

    private void boot(){
        mySendService.sendReport();
    }
}

}

现在在Application.class的onCreate方法中添加代码:

public class Foreground implements Application.ActivityLifecycleCallbacks {

public static final long CHECK_DELAY = 500;
public static final String TAG = Foreground.class.getName();

public interface Listener {

    public void onBecameForeground();

    public void onBecameBackground();

}

private static Foreground instance;

private boolean foreground = false, paused = true;
private Handler handler = new Handler();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
private Runnable check;

/**
 * Its not strictly necessary to use this method - _usually_ invoking
 * get with a Context gives us a path to retrieve the Application and
 * initialise, but sometimes (e.g. in test harness) the ApplicationContext
 * is != the Application, and the docs make no guarantees.
 *
 * @param application
 * @return an initialised Foreground instance
 */
public static Foreground init(Application application) {
    if (instance == null) {
        instance = new Foreground();
        application.registerActivityLifecycleCallbacks(instance);
    }
    return instance;
}

public static Foreground get(Application application) {
    if (instance == null) {
        init(application);
    }
    return instance;
}

public static Foreground get(Context ctx) {
    if (instance == null) {
        Context appCtx = ctx.getApplicationContext();
        if (appCtx instanceof Application) {
            init((Application) appCtx);
        }
        throw new IllegalStateException(
                "Foreground is not initialised and " +
                        "cannot obtain the Application object");
    }
    return instance;
}

public static Foreground get() {
    if (instance == null) {
        throw new IllegalStateException(
                "Foreground is not initialised - invoke " +
                        "at least once with parameterised init/get");
    }
    return instance;
}

public boolean isForeground() {
    return foreground;
}

public boolean isBackground() {
    return !foreground;
}

public void addListener(Listener listener) {
    listeners.add(listener);
}

public void removeListener(Listener listener) {
    listeners.remove(listener);
}

@Override
public void onActivityResumed(Activity activity) {
    paused = false;
    boolean wasBackground = !foreground;
    foreground = true;

    if (check != null)
        handler.removeCallbacks(check);

    if (wasBackground) {
        Log.i(TAG, "went foreground");
        for (Listener l : listeners) {
            try {
                l.onBecameForeground();
            } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
            }
        }
    } else {
        Log.i(TAG, "still foreground");
    }
}

@Override
public void onActivityPaused(Activity activity) {
    paused = true;

    if (check != null)
        handler.removeCallbacks(check);

    handler.postDelayed(check = new Runnable() {
        @Override
        public void run() {
            if (foreground && paused) {
                foreground = false;
                Log.i(TAG, "went background");
                for (Listener l : listeners) {
                    try {
                        l.onBecameBackground();
                        Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
                        if (intent != null) {
                            // We found the activity now start the activity
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else {
                            // Bring user to the market or let them choose an app?
                            intent = new Intent(Intent.ACTION_VIEW);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
                            startActivity(intent);
                        }
                    } catch (Exception exc) {
                        Log.e(TAG, "Listener threw exception!", exc);
                    }
                }
            } else {
                Log.i(TAG, "still foreground");
            }
        }
    }, CHECK_DELAY);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}

@Override
public void onActivityStarted(Activity activity) {
}

@Override
public void onActivityStopped(Activity activity) {
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}

@Override
public void onActivityDestroyed(Activity activity) {
}

您必须在onActivityPaused()方法中设置应用程序的包名称。 谢谢

答案 1 :(得分:0)

执行onPause中的代码

@Override
protected void onPause() {

    Toast.makeText(getApplicationContext(),"Background",Toast.LENGTH_LONG).show();
    super.onPause();
}

因此,如果应用程序进入后台,您将获得吐司。 希望它有所帮助..所有最好的

答案 2 :(得分:-2)

尝试使用服务。阅读http://developer.android.com/guide/components/services.html

的更多信息