繁体   English   中英

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

[英]how to start activity when the main activity is running in background?

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

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

@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);

}

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

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

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

谢谢。

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

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

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

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

要完成Hemendra的答案,除了FLAG_ACTIVITY_REORDER_TO_FRONT之外,您不需要任何其他标志。 您只需要从正常意图创建PendingIntent并调用新的PendingIntent的send()方法来调度intent。 我是这样做的:

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()));
}
Intent i= new Intent("android.intent.category.LAUNCHER");
i.setClass(getApplicationContext(), MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent i2 = PendingIntent.getActivity(getApplicationContext(), 0, insIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
try {
     i2.send(getApplicationContext(), 0, i);
} catch (Exception e) {
     e.printStackTrace();
}

在MyActivity的onCreate上......

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

如果主要活动在后台运行,这将把您的活动带到前台活动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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