[英]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()之后)有没有人知道如何中断逻辑以便从主活动启动活动?
谢谢。
要完成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.