0

这是一个谷歌聊天应用程序。当我收到来自 Google Chat 的消息时,我想在活动处于后台时将其作为通知显示在状态栏中。

我尝试在方法中设置布尔值,onPause()但它不起作用。

public void addMessage(String chatid, String msg) {
    // I want to the execute this line only when the activity is in background
    notify.getCurrentActivity(getApplicationContext(), msg, fromName, chatid);
}

public void getCurrentActivity(Context context, String msg){
    showNotification(context, msg, fromName, fromChatID);
}
4

2 回答 2

0

我自己找出解决方案

私有 int 密钥;// 声明为全局

受保护的无效 onPause

{

键=1;

super.onpause();

}

受保护的无效 onResume{

键=0;

超级.onResume();

}

public void addMessage(String chatid, String msg) {

如果(键==1)

{

notify.getCurrentActivity(getApplicationContext(), msg, fromName, chatid);

}

}

于 2012-09-12T05:30:31.400 回答
0

尝试在下面做

try{
    boolean foregroud = new ForegroundCheckTask().execute(context).get();


        if(foregroud)
        {
            //app is foreground 
        }

        else
        {
            //app is not foreground         }
    }catch(Exception e)
    {
        e.toString();
    }

在下面添加异步

    //Foreground check
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

      @Override
      protected Boolean doInBackground(Context... params) {
        final Context context = params[0].getApplicationContext();
        return isAppOnForeground(context);
      }

      private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
          return false;
        }
        final String packageName = context.getPackageName();
        for (RunningAppProcessInfo appProcess : appProcesses) {
          if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
            return true;
          }
        }
        return false;
      }
    }
于 2012-09-11T06:44:37.843 回答