10

onMessage()GCM から受信したときに、アプリケーションが開いていて、現在ユーザーに表示されているかどうかを確認する方法を知りたいです。最初は独自の を使用していましboolean isVisibleたが、アプリが開いていない場合、そのフラグにアクセスするために使用するオブジェクトは であるため、これは信頼できないことに気付きましたnull。これ自体を使用してアプリが開いているかどうかを確認できますが、少し面倒です。アプリケーションが現在開いているかどうか、およびユーザーがアプリを表示しているかどうかを何らかの方法でチェックするシステム レベルから Android に方法はありますか? ユーザーが最近「ホーム」ボタンを押してアプリをバックグラウンドに送信したため、アプリが技術的には実行されていても、表示されていない可能性があることに注意してください。

@Override
protected void onMessage(Context arg0, Intent arg1) {
    String turn = intent.getExtras().getString("turn");
    if (turn.equals("yours"){
         if (/*app is open*/){ <------------------ what can go here?
             // dont generate a notification
             // display something in the game instead
         }
         else{
             // generate notification telling player its their turn
         }
    }
}
4

4 に答える 4

2

ブール値の isVisible を保存する SharedPreferences を使用します。設定から値を取得すると、デフォルト値を追加できます。

SharedPreferences settings = context.getSharedPreferences("NAME_XXX", Activity.MODE_PRIVATE);
settings.getBoolean("visible", false);
于 2013-04-11T11:10:20.443 に答える
1

私がいつもしているのは、現在のアクティビティへの参照です。

すべての onResume で現在のアクティビティをこれに設定し、すべての onPause で null に設定します。

現在のアクティビティが null の場合、アプリは開いていません。null でない場合は、正しいアクティビティが開いているかどうかを確認し、そのアクティビティに配信できます。

GCMIntentService:

public static Activity currentActivity;
public static final Object CURRENTACTIVIYLOCK = new Object();

    @Override
protected void onHandleIntent(Intent intent) {
    synchronized(CURRENTACTIVIYLOCK) {
        if (currentActivity != null) {
            if (currentActivity.getClass() == CorrectActivity.class) {
                CorrectActivity act = (CorrectActivity)currentActivity;
                act.runOnUiThread(new Runnable() {
                    public void run() {
                        // Notifiy activity
                    }
                });
            } else {
               // show notification ?
            }
        } else {
            // show notification
        }
    }
}

正しいアクティビティ:

@Override
    protected void onResume() {
        synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
                GCMIntentService.currentActivity = this;
            }
        }
        super.onResume();
    }

@Override
    protected void onPause() {
        synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
            GCMIntentService.currentActivity = null;
        }
        super.onPause();
    }
于 2013-04-11T12:47:27.700 に答える
0

私のために働いたこと:

最終的なクラス定数を作成し、その中に静的変数を作成します。

public final class Constants{
public static AppCompatActivity mCurrentActivity;
}

今、あなたの活動のそれぞれの履歴書で次のように言います:

    @Override
    protected void onResume() {
        super.onResume();
        Constants.mCurrentActivity = this;
    }

通知を受け取ったら、現在のアクティビティが null かどうか、null の場合はアプリケーションが開かれていないかどうか、アクティビティが null でない場合は、次のようなことを確認できます。

if(Constants.mCurrentActivity instanceof MainActivity){
   ((MainActivity) Constants.mCurrentActivity).yourPublicMethodOrStaticObject;
}
于 2016-04-19T12:05:52.050 に答える