仅在活动处于后台时显示来自Google聊天活动的通知

时间:2012-09-11 06:39:36

标签: android

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

我尝试在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);
}

2 个答案:

答案 0 :(得分:0)

尝试在下面进行

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


        if(foregroud)
        {
            //app is foreground 
        }

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

添加以下async

    //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;
      }
    }

答案 1 :(得分:0)

我自己找出解决方案

private int key; //声明为全局

protected void onPause

{

键= 1;

super.onpause();

}

protected void onResume {

键= 0;

super.onResume();

}

public void addMessage(String chatid,String msg){

如果(键== 1)

{

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

}

}