我有一个针对移动设备优化的 Web 应用程序,我想制作一个 Android 应用程序(一个简单的 WebView,用于加载该 Web 应用程序),以便发送 GCM 推送通知。
我的代码(没有不重要的行)。
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®istrationId=" + 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(在 Native App 中不可用)和 registrationId 之间的关联。
对我来说最好的解决方案是在每次 onRegistered 调用后重新加载 WebView 并将 registrationId 作为参数添加到 URL。但是因为我在这个方法中没有引用 MainActivity,所以我不知道如何重新加载 WebView。 我需要用 BroadcastManager 做这样的事情还是有其他方法?
最佳答案
您可以分两步完成此操作,而无需重新加载 WebView :
在 webview Activity 中,您应该有一个名为
mWebView
的成员变量分配给onCreate
中的 webview 实例.在 webview Activity 中,动态注册一个基于类的 BroadcastReceiver,该类是您的 webview Activity 的内部类。内部类将允许您访问
mWebView
上面 #1 中定义的成员变量。在服务中,使用
sendBroadcast
发送registrationId
到 WebView Activity 中的 BroadcastReceiver。从 webview Activity 中的 BroadcastReceiver,您可以使用
mWebView.loadUrl("javascript:myJavascriptRegistrationReceiver('<registrationId>')");
将信息发送到 webview 而无需重新加载页面。
下面的链接解释了 sendBroadcast()
和 BroadcastReceiver
在应用程序组件之间传输信息:
http://www.cs.umd.edu/class/fall2011/cmsc436/CMSC436/Lectures_Labs_files/BroadcastReceivers.pdf
如果您喜欢冒险和/或想要最新的“热点”,那么您可以使用 Square 的 Otto [1] 或 GreenRobot 的 EventBus [2] 等事件总线在您的服务和 Activity 之间传递消息。这些是 BroadcastReceivers 的替代品,通常可以减少样板代码的数量。
关于android - 注册到 GCM 推送通知后如何重新加载 Android Webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14892657/