0

このGoogleガイドのおかげでGCM登録ID(プッシュ通知用)を受け取り、reg.idをデータベースに保存でき、認証なしですべて正常に動作します。Web API 2、oauth 2 認証、およびアカウント マネージャーを使用しています。

1) ユーザーがアプリケーションにサインインすると、アプリはユーザーのアカウントを作成します。
- または、アカウントが存在する場合は、ユーザーを自動サインインし
ます
。前に受け取ったID。そうでない場合、アプリは登録を要求します。GCM から id を取得し、Volley を介してサーバーに投稿し (ここでは AuthToken が必要です)、アプリはその reg のアカウントにユーザーデータを設定します。idを受け取りました。

現時点では私の頭の中にしか存在しない私のアプリの上記の流れで、いくつか質問があります。

まず、ガイドに従って、最初に認証トークンを取得し、IntentService であるステップ 3 に移動するにはどうすればよいですか。

次に、最初の質問ができたとしましょう。ユーザーが別のデバイスから自分のアカウントにログインするとどうなりますか? 彼の登録を更新する必要がありますか。彼の新しいデバイスのID。しかし、このデバイスが一時的なもので、彼が恒久的なデバイスを使用するために戻ってきた場合はどうなるでしょうか? 最後にサインインしたデバイスが一時デバイスだったため、通知は一時デバイスに送信されます。

私は本当に混乱しており、私の道を照らしてくれる人には感謝しています. ありがとう。

編集

Google のガイドに従う代わりに (IntentService を使用する代わりに)、AsyncTask で認証トークンと登録 ID(トークン) の両方を取得することは可能ですか?

4

2 に答える 2

1

質問の2番目の部分の回答と同じです。ユーザーとその regId の関係は 1 対 n である必要があります。したがって、1 人のユーザーが複数のデバイスを持つことができ、この複数の regId によって. このユーザーにメッセージを送信する場合は、複数のメッセージを送信する必要があります (すべてのデバイスに 1 つ)。他の可能な解決策は、最近導入されたDevice Group Messagingを使用することであり、IMO が望ましい方法です。

于 2015-08-24T13:00:36.367 に答える
0

ご回答ありがとうございます。2 つの非同期タスクを使用している場合にのみ機能し、これが私の解決策です。批判や推奨事項は大歓迎です。

TokenCheckerActivity を作成し、ログイン アクティビティとメイン アクティビティの間に配置します。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_token_checker);

    webApiUri = "url Here";
    tokenContext = this;

    accountManager = accountManager.get(tokenContext);
    PpSharedPreferences ppSharedPreferences = new PpSharedPreferences(tokenContext);
    ppAuthenticator = new PpAuthenticator(tokenContext);

    account = ppAuthenticator.getCurrentAccount(ppSharedPreferences.getUsername());

    new GetAuthorizationToken().execute(ppSharedPreferences.getUsername());
}

非同期タスク

/**
 * Gets the authorization token and checks if GCM registration id received.
 * Gets reg is if not exists.
 */
private class GetAuthorizationToken extends AsyncTask<String,Void,String>{
    @Override
    protected String doInBackground(String... params) {
        String username = params[0];
        String mAuthToken = ppAuthenticator.getPpAuthToken(username);
        return mAuthToken;
    }

    @Override
    protected void onPostExecute(String authToken) {
        if(!TextUtils.isEmpty(authToken))
        {
            final String gcmTokenSent = accountManager.getUserData(account, AccountGeneral.GCM_REGISTRATION_ID);
            if (gcmTokenSent == null || !gcmTokenSent.equals("true")) {
                new GetGcmRegistrationToken().execute(authToken);
            } else {
                // We have the Gcm Registration Id continue to the main activity
                Intent intent = new Intent(tokenContext, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }
}


private class GetGcmRegistrationToken extends AsyncTask<String,Void,PpTokens>{
    @Override
    protected PpTokens doInBackground(String... params) {
        PpTokens tokens = new PpTokens();
        tokens.setAuthToken(params[0]);
        try {
            if (checkPlayServices()) {
                InstanceID instanceID = InstanceID.getInstance(tokenContext);
                String regToken = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                tokens.setRegToken(regToken);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return tokens;
    }

    @Override
    protected void onPostExecute(PpTokens tokens) {
        if (!TextUtils.isEmpty(tokens.getRegToken()))
        {
            sendRegistrationToServer(tokens.getRegToken(),tokens.getAuthToken());
        }
    }
}

    private class PpTokens
{
    private String authToken;
    private String regToken;

    public String getAuthToken() {
        return authToken;
    }

    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }

    public String getRegToken() {
        return regToken;
    }

    public void setRegToken(String regToken) {
        this.regToken = regToken;
    }
}

登録 ID をサーバーに送信する

private void sendRegistrationToServer(String regToken, final String authToken) {
    final String tag_json_obj = "json_obj_req";
    String url = webApiUri + "?gcmRegistrationToken=" + regToken;

    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                Log.d("Name for Reg Token:", response.getString("Name"));

                // You should store a boolean that indicates whether the generated token has been
                // sent to your server. If the boolean is false, send the token to your server,
                // otherwise your server should have already received the token.
                accountManager.setUserData(account, AccountGeneral.GCM_REGISTRATION_ID, "true");

                Intent intent = new Intent(tokenContext, MainActivity.class);
                startActivity(intent);
                finish();

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            String errorMessage = JsonErrorMessageHandler.onErrorResponse(error);
            accountManager.setUserData(acc, AccountGeneral.GCM_REGISTRATION_ID, "false");
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "Bearer " + authToken);
            return headers;
        }
    };

    int socketTimeout = 5000;
    int maxRetries = 3;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    objectRequest.setRetryPolicy(policy);

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(objectRequest, tag_json_obj);
}
于 2015-08-25T07:48:36.553 に答える