主活动在后台运行时如何启动活动?

Nik*_*lin 3 android android-activity

我创建了一个应用程序,使用户能够在应用程序以后台模式运行时设置是否要接收通知.如果启用了通知,则应启动活动(对话框应显示在屏幕上).

我尝试通过以下方式启用它:

@Override
public void onProductsResponse(List<Product> products) {
    this.products = products;
    moboolo.setProducts(products);
    if(moboolo.getAutomaticNotificationsMode() != 0 && products.size() > 0){
        if(isRunningInBackground)
        {
            Intent intent = new Intent(this, ProductListActivity.class);
            intent.setAction(Intent.ACTION_MAIN);
            startActivity(intent);
        }
    }
    drawProducts(products);

}
Run Code Online (Sandbox Code Playgroud)

这是主要活动的方法.当onPause()执行时,isRunningInBackground设置为true.当我尝试在主应用程序在后台运行时调试它

startActivity(intent)没有效果(活动没有出现).

当主要活动在后台运行时(调用onPause()之后)有没有人知道如何中断逻辑以便从主活动启动活动?

谢谢.

Dav*_*ebb 7

您无法强制Activity从运行后台的应用程序中显示. 文件说:

如果应用程序在后台运行并需要用户注意,应用程序应创建一个通知,允许用户在他或她方便时做出响应.

如果您Activity暂停,则用户可能在其他应用程序中执行其他操作,并且可能不希望您Activity突然出现在他们当前正在执行的操作之上.

您应该使用状态栏通知.这允许您的应用程序在状态栏中放置一个图标.然后,用户可以向下滑动状态栏抽屉,然后单击您的通知以打开您的应用程序并显示相关信息Activity.这是绝大多数Android应用程序在后台运行时通知用户的方式.


Jav*_*deh 5

要完成 Hemendra 的答案,除了 之外,您不需要任何这些标志FLAG_ACTIVITY_REORDER_TO_FRONT。您只需根据正常意图创建一个 PendingIntent 并调用新的 PendingIntent 的 send() 方法来分派该意图。我是这样做的:

Intent yourIntent = new Intent(this, YourActivity.class);
// You can send extra info (as a bundle/serializable) to your activity as you do 
// with a normal intent. This is not necessary of course.
yourIntent.putExtra("ExtraInfo", extraInfo); 
// The following flag is necessary, otherwise at least on some devices (verified on Samsung 
// Galaxy S3) your activity starts, but it starts in the background i.e. the user
// doesn't see the UI
yourIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, 
                                                        yourIntent, 0);
try {
    pendingIntent.send(getApplicationContext(), 0, yourIntent);
} catch (Exception e) {
    Log.e(TAG, Arrays.toString(e.getStackTrace()));
}
Run Code Online (Sandbox Code Playgroud)