3

モバイルに最適化された Web アプリがあり、GCM プッシュ通知を送信するために、Android アプリ (Web アプリをロードする単純な WebView) を作成したいと考えています。

私のコード(重要でない行なし)。

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Webview 
        WebView webView = (WebView) findViewById(R.id.webView);
        webView.loadUrl("http://" + HOST + "?type=android&registrationId=" + REGISTRATIONID);       

        // GCM Registration                   
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
          GCMRegistrar.register(this, "SENDERID");
          Log.i("TAG", "Registered! ");
        } else {
          Log.i("TAG", "Already registered");
        }
    }
}

GCMIntentService クラスを実装 (コピーペースト) したよりも

public class GCMIntentService extends GCMBaseIntentService {

    public GCMIntentService() {
        super("SENDERID");
    }

    protected void onRegistered( Context arg0, String registrationId ) {
        Log.i( "TAG", "Registration id is: " + registrationId );
    }    

    protected void onError( Context arg0, String errorId ) {}
    protected void onMessage( Context arg0, Intent intent ) {}
    protected void onUnregistered( Context arg0, String registrationId ) {} 
}

これまでのところ問題なく動作します。WebView は正しいコンテンツをロードし、onRegistered メソッドが呼び出され、registrationId を LogCat に表示します。

残念ながら、ここから先に進む方法がわかりません。最後に必要なのは、UserId (ネイティブ アプリでは使用できません) と registrationId の相関関係です。

私にとって最善の解決策は、各 onRegistered 呼び出しの後に WebView をリロードし、registrationId をパラメーターとして URL に追加することです。しかし、このメソッドには MainActivity への参照がないため、WebView をリロードする方法がわかりません。BroadcastManagerでそのようなことをする必要がありますか、それとも他の方法がありますか?

4

1 に答える 1

2

これは、webview をリロードすることなく、2 つのステップで実行できます。

  1. webview アクティビティにはmWebView、 の webview インスタンスに割り当てられるというメンバー変数が必要onCreateです。

  2. webview アクティビティで、webview アクティビティの内部クラスであるクラスに基づく BroadcastReceiver を動的に登録します。内部クラスにより、mWebView上記の #1 で定義されたメンバー変数にアクセスできます。

  3. サービスでは、WebView アクティビティで BroadcastReceiver にsendBroadcastを送信するために使用します。registrationId

  4. webview アクティビティの BroadcastReceiver から、次を使用してページをリロードする必要なく、webview に情報を送信できます。mWebView.loadUrl("javascript:myJavascriptRegistrationReceiver('<registrationId>')");

以下のリンクでは、アプリ コンポーネント間で情報を送信 する方法について説明sendBroadcast()しています。BroadcastReceiver

冒険好きで最新の「ホット」が必要な場合は、Square の Otto [1] や GreenRobot の EventBus [2] などのイベント バスを使用して、サービスとアクティビティの間でメッセージをやり取りできます。これらは一般的に定型コードの量を削減する BroadcastReceivers の代替品です。

[1] https://github.com/square/otto

[2] https://github.com/greenrobot/EventBus

于 2013-02-15T22:36:06.010 に答える