2012-09-19 33 views
3

我正在将GCM(Google云消息传递)应用到我的应用程序中。在GCM onMessage中显示对话框()

我在谷歌教程中设置了所有这些,并且它工作到目前为止。

onMessage调用GCMIntentService时,我在通知栏中显示通知。

现在我有一个方法告诉我,如果应用程序是在前台或没有。 当应用程序处于后台时,它会在栏中显示没有问题的通知。

但是我怎样才能向用户显示一个对话框?

当我打电话:

AlertDialog.Builder builder = new AlertDialog.Builder(context); 

其中上下文是从onMessage()给定的情况下,我当然这个错误:

_Notification.showPopUp() Error: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

所以我试图用MainActivity.this更换背景下,为了这个目的我将它保存在一个静态变量中;但是当我现在运行它时,没有任何反应,没有错误,没有对话框出现。

我的对话框代码:

private static AlertDialog.Builder myAlertDialog; 

private static void showPopUp(Context context,String kind, String resource_name, Integer resource_id) 
{ 
    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
builder.setMessage("Are you sure you want to exit?") 
     .setCancelable(false) 
     .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
     { 
     public void onClick(DialogInterface dialog, int id) 
      { 
      } 
     }) 
     .setNegativeButton("No", new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface dialog, int id) 
      { 
       dialog.cancel(); 
      } 
     }); 

    AlertDialog alert = builder.create(); 
alert.show(); 

Log.e("TEST","alert.show()"); 
} 

的最后一个日志:alert.show()被显示在logcat中,但没有错误。

规格: 捉迷藏设备(银河S2)上 的Android 4.0.3

可能有人请告诉我什么是错我的代码,或没有任何人知道的一些解决方法吗?

编辑:

private static Context context_forshowingPopUp = null; 

的onCreate

//Set the context for showing a popup View 
_Notification.setContext_forshowingPopUp(this); 

AlertDialog.Builder builder = new AlertDialog.Builder(getContext_forshowingPopUp()); 

public static Context getContext_forshowingPopUp() 
{ 
    return context_forshowingPopUp; 
} 

public static void setContext_forshowingPopUp(Context context_forshowingPopUp) 
{ 
    _Notification.context_forshowingPopUp = context_forshowingPopUp; 
} 
+0

对于记录:如果应用程序是不是在前台,您仍然可以使用通知区域。请参见类NotificationManager。 –

+0

是的,我知道,但当用户在应用程序中已准备就绪时,用户在通知栏中收到通知似乎不是很合逻辑。有没有关于这种用例的android设计模式的信息? – user1683272

+0

只需在某些静态可访问的位置维护指向当前活动的指针。将其设置在应用程序中每个活动的onResume()中,并在onPause()中清除。如果所有活动都来自自定义共同基础,则可以提供帮助。 –

回答

1

必须使用YourCurrentActivity.this作为背景,同时建立Alertdialog:

,我救我MainActivity.this的一部分。你可以像下面这样解决。

一流:

public class Config{ 
    public static Context context; 

    } 

当你的活动造成的,只要设置Config.contex

public class MyActivity extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
     Config.context=this; 
    ...} 
    //other stuffs 

     } 

在的onMessage

showPopUp(Config.context,kind, resource_name, resource_id); 
+0

我有一个私人静态上下文context_forshowingPopUp;我的确做得和你一样。但它不起作用。我会更新我的问题,以显示这部分。谢谢 – user1683272

+0

java.lang.RuntimeException:Handler(android.view.ViewRootImpl){41929ee8}将消息发送到处理程序的死线程 - 是我得到这个解决方案的日志猫 – David

+0

我想说这是全球化的另一个原因状态是错误的:保持对主要活动的引用并不能保证此活动在需要时保持活跃状态​​。 – ereOn