2010-01-10 70 views
3

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

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

@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(意图)没有任何效果(活动没有出现)。

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

谢谢。

回答

7

您不能强制Activity从运行后台的应用程序中出现。 The documentation says

如果应用程序在后台运行,需要用户的关注,应用程序应该创建一个notificaiton,它允许用户在他或她方便回应。

如果您Activity暂停用户可以做不同的应用程序别的东西,可能不希望自己的Activity突然出现在目前他们正在做的事情上面。您应该使用Status Bar Notification。这允许您的应用程序在状态栏中放置一个图标。用户然后可以滑下状态栏抽屉并单击您的通知以打开您的应用程序并显示相关的Activity。这是绝大多数Android应用程序在后台运行时通知用户的方式。

+0

太棒了!这更好。 – 2010-01-10 13:28:36

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

如果主要业务是在后台运行,这将使您的活动,以正面的事件。

2

要完成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())); 
} 
+0

谢谢,在这里使用PendingIntent对我来说是关键。以前,我试图直接调用startActivity,但没有奏效。 – 2016-09-14 14:43:39