[英]Push Notifications using GCM on Android
我正在嘗試在我的Android應用程序上實現推送通知。 所以沒有比Googles Developers頁面更好的起點了。
我想在這里學習這個教程: GCM演示應用程序 。 教程建議使用通過SDK Manager提供的示例代碼。 執行此操作並嘗試發送推送通知后,當應用程序運行時,我會在屏幕上看到正在寫入新推送已到達。
但是,當應用程序在后台或未運行時,我沒有得到推送通知 。 如果我打開應用程序,屏幕上會再次顯示消息。 但我從來沒有通過彈出和聲音通知的形式。
我手動必須在android中執行此操作嗎? 我認為它與iOS類似,平台負責向您顯示通知。
我有什么想法可以實現它嗎?
但我從來沒有通過彈出和聲音通知的形式。
觸發通知時,聲音可以編程到代碼中。 用這樣的話說。
Notification notification = new Notification(icon, tickerText, when);
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
但是,當應用程序在后台或未運行時,我沒有得到推送通知
我手動必須在android中執行此操作嗎? 我認為它與iOS類似,平台負責向您顯示通知。
您的應用程序始終會發送GCM數據(推送通知)。 您如何處理這些數據取決於您。 GCM意向服務負責向您提供數據,就是這樣。 您需要使用通知服務向用戶顯示相應的通知。
這種方法有優點/缺點。 當您收到推送通知時,應用程序代碼將在Android上運行,而iPhone上並非如此。 您還可以靈活地根據推送通知的類型進行更新或通知用戶。
在應用啟動時向您的設備注冊發件人ID,您應該按預期收到通知。 所有推送通知都將在您選擇的GCMIntentService上傳遞給此方法protected void onMessage(Context context, Intent intent)
。
嘗試重新注冊並重新注冊您的設備。 在DemoActivity.java中
final String regId = GCMRegistrar.getRegistrationId(this);
GCMRegistrar.unregister(this);
然后,刪除GCMRegistrar.unregister(this);
在第二次發射。
更新
您的申請中的通知:
創建類
public class DemoApplication extends Application {
private class NotifyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "RECEIVE MESSAGE", Toast.LENGTH_SHORT).show();
}
}
private NotifyReceiver notifyReceiver = new NotifyReceiver();
@Override
public void onCreate() {
registerReceiver(notifyReceiver, new IntentFilter("GCM_MESSAGE"));
super.onCreate();
}
@Override
public void onTerminate() {
unregisterReceiver(notifyReceiver);
super.onTerminate();
}
}
然后把
<application
android:name=".DemoApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
在AndroidManifest.xml中發送廣播
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = getString(R.string.gcm_message);
displayMessage(context, message);
context.sendBroadcast(new Intent("GCM_MESSAGE"));
// notifies user
generateNotification(context, message);
}
作為替代案例,您可以在Manifest,Activity或ForeGround Service中注冊broadcastReceiver
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.