2012-09-24 3 views
13

이 튜토리얼의 푸시 알림 응용 프로그램 Android을 개발했습니다 : push notification in android app. 앱을 실행하면 등록 버튼이 표시됩니다. 등록 단추를 클릭하고 등록이 성공하면 장치에 알림이 표시됩니다.내 자신의 안드로이드 애플 리케이션에 푸시 알림을 추가하는 방법

어떻게 내 응용 프로그램에 포함시킬 수 있습니까? 내 응용 프로그램에는 하나의 xml 파싱 예제 응용 프로그램이 있습니다. 여기에 새 항목이 추가되면 장치에 알림 메시지가 표시됩니다 (새 주문이 표시됨). 여기에 자동으로 생성됩니다.

+2

C2DM가되지 않습니다를 따르십시오. https://developer.android.com/guide/google/gcm/index.html – gigadot

+0

을 사용하십시오. 위의 튜토리얼을 배우고 개발하려고합니다. – user1676640

+1

내 대답을보세요. 도움이 되길 바랍니다. http : // stackoverflow. com/a/12437549/554740 – HelmiB

답변

17

Google Cloud Messaging의 데모 신청서를 게시하고 있습니다.

이 서비스를 사용하기에 - 적어도 하나의 로그인 Google 계정에 API 레벨과 같거나

구글 API와 안드로이드 OS 2.2 이상 사용자와 데모 응용 한을 작성해야합니다.

먼저 GCM library을 추가해야합니다.

package com.example.gcmdemo; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 

import com.google.android.gcm.GCMRegistrar; 

public class MainActivity extends Activity { 

    private static final String TAG = "Push Notification Demo Activity"; 
    private static final String SENDER_ID = "1069713227710"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     GCMRegistrar.checkDevice(this); 
     GCMRegistrar.checkManifest(this); 
     final String regId = GCMRegistrar.getRegistrationId(this); 
     if (regId.equals("")) { 
      GCMRegistrar.register(this, SENDER_ID); 
     } else { 
      Log.v(TAG, "Already registered : "+regId); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
} 

그리고 마지막으로 데모 매니페스트 :

여기
package com.example.gcmdemo; 

import android.content.Context; 
import android.content.Intent; 
import android.util.Log; 

import com.google.android.gcm.GCMBaseIntentService; 
import com.google.android.gcm.GCMConstants; 

public class GCMIntentService extends GCMBaseIntentService { 

    private static final String TAG = "Push Notification Demo GCMIntentService"; 

    @Override 
    protected void onError(Context context, String errorId) { 

     if(GCMConstants.ERROR_ACCOUNT_MISSING.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Account Missing"); 
     } else if(GCMConstants.ERROR_AUTHENTICATION_FAILED.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Authentication Failed"); 
     } else if(GCMConstants.ERROR_INVALID_PARAMETERS.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Invalid Parameters"); 
     } else if(GCMConstants.ERROR_INVALID_SENDER.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Invalid Sender"); 
     } else if(GCMConstants.ERROR_PHONE_REGISTRATION_ERROR.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Phone Registration Error"); 
     } else if(GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.equalsIgnoreCase(errorId)) { 
      Log.v(TAG, "Error Service Not Available"); 
     } 
    } 

    @Override 
    protected void onMessage(Context context, Intent intent) { 

     // App Server Sends message as key value pairs 
     String value1 = intent.getStringExtra("key1"); 
     String value2 = intent.getStringExtra("key2"); 

     Log.v(TAG, "key1: "+value1); 
     Log.v(TAG, "key2: "+value2); 
    } 

    @Override 
    protected void onRegistered(Context context, String regId) { 

     Log.v(TAG, "Successfull Registration : "+regId); 
    } 

    @Override 
    protected void onUnregistered(Context context, String regId) { 

     Log.v(TAG, "Successfully Unregistred : "+regId); 
    } 

    @Override 
    protected String[] getSenderIds(Context context) { 
     return super.getSenderIds(context); 
    } 

    @Override 
    protected void onDeletedMessages(Context context, int total) { 
     super.onDeletedMessages(context, total); 
    } 

    @Override 
    protected boolean onRecoverableError(Context context, String errorId) { 
     return super.onRecoverableError(context, errorId); 
    } 
} 

당신이 데모 활동 다음에 등록을 확인하는 방법입니다 : 다음과 같이 GCMBaseIntentService를 확장 내가 GCMIntentService라는 이름의 클래스를 만드는 것보다

:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.gcmdemo" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="8" /> 

    <permission 
     android:name="com.example.gcmdemo.permission.C2D_MESSAGE" 
     android:protectionLevel="signature" /> 

    <uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE" /> 

    <!-- App receives GCM messages. --> 
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 
    <!-- GCM connects to Google Services. --> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <!-- GCM requires a Google account. --> 
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    <!-- Keeps the processor from sleeping when a message is received. --> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 

    <application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/title_activity_main" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver 
      android:name="com.google.android.gcm.GCMBroadcastReceiver" 
      android:permission="com.google.android.c2dm.permission.SEND" > 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
       <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 

       <category android:name="com.example.gcmdemo" /> 
      </intent-filter> 
     </receiver> 

     <service android:name=".GCMIntentService" /> 
    </application> 

</manifest> 

또한 n eed third party server side script as specified here.

+0

예 위의 methods.the 응용 프로그램이 성공적으로 실행하고 표시 listview.i 내 데이터베이스에 하나의 항목을 삽입해야합니다 내가 가서 장치를 볼거야 아무 통지 메시지가 내 장치에 표시됩니다. – user1676640

+0

GCM에서 푸시 알림의 양을 제한 하시겠습니까? –

2

개인적으로 대신 GCM의 PushNotification에 대한 Parse라는 이름의 다른 도서관도 있음을 제안, 그것은 Google 클라우드 메시징과 동일한 작동하지만 그 다음 이렇게

당신은 단지 JAR 파일을 다운로드해야 GCM

너무 너무 너무 쉽다 및 PUSH-통지 코드의 간단한 2-3 라인

는 PHP 또는 서버 측 코드의 어떤 종류를 사용하지 않아도이 사이트 비록 당신 https://parse.com/tutorials/android-push-notifications

를 사용 배울 당신 시설 제공

당신은 그들이

을 제공하는 UI의 그림을 보면 좋은 UI를 제공 전송 알림 원한다면 6,

보면 내가 유 코드 위에서

Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY"); 
    PushService.setDefaultPushCallback(this, YourDefaultActivity.class); 

데모 줄 것이다 것은 푸시 알림

를 수신 위해 충분하다

enter image description here

+1

구문 분석은 상업용 제안입니다. GCM은 일정한 한도를 초과 한 유사한 제한 사항 (가격)을 갖고 있습니까? –

+0

구문 분석은 SaaS 모델에서만 상용입니다. 그들도 github에 자신의 서버의 오픈 소스 버전을 가지고 – kacper3w

2

FCM

사용하여 푸시 알림을 보내기 구글은 Google 클라우드 메시징 (GCM)를 사용되지 않으며 중포 기지 클라우드 메시징 (FCM) 인 새로운 푸시 알림 서버를 출시했다. FCM은 GCM 같은 동일 FCM은

중포 기지 클라우드 메시징 메시지의 세 가지 유형 (Message types)

1.Notification 메시지

을 보낼 수 있습니다 또한 모바일 플랫폼을위한 크로스 플랫폼 메시징 솔루션 모두 알림 및 데이터

0,123,516와 2.Data 메시지

3.message

중포 기지 클라우드 메시징 통합 단계 : -

1.SetUp 새 프로젝트 또는 Firbase 콘솔에서 가져 오기 프로젝트 (https://firebase.google.com/)

2.Add 동일한 패키지 이름의 Firebase 앱의 앱.

3. "google-services.json"파일을 가져 와서 해당 파일을 프로젝트의 응용 프로그램 폴더에 저장하십시오.이 파일에는 Google 서비스의 모든 URL과 키가 포함되어 있으므로이 파일을 변경하거나 편집하지 마십시오.

4. Project for Firebase에 새로운 Gradle 종속성을 추가하십시오.

//app/build.gradle 
dependencies { 
    compile 'com.google.firebase:firebase-messaging:9.6.0' 
} 

apply plugin: 'com.google.gms.google-services' 

5. 우리가 FCM을 위해 앱에서 사용하는 모든 상수 값을 포함하는 클래스를 만듭니다.

public class Config { 
public static final String TOPIC_GLOBAL = "global"; 
// broadcast receiver intent filters 
public static final String REGISTRATION_COMPLETE = "registrationComplete"; 
public static final String PUSH_NOTIFICATION = "pushNotification"; 

// id to handle the notification in the notification tray 
public static final int NOTIFICATION_ID = 100; 
public static final int NOTIFICATION_ID_BIG_IMAGE = 101; 
public static final String SHARED_PREF = "ah_firebase"; 
} 

6.

는 것입니다 각 응용 프로그램에 대해 고유합니다 중포 기지 등록 ID를 수신라는 클래스 MyFirebaseInstanceIDService.java를 만듭니다. 등록 ID는 단일 장치로 메시지를 보내는 데 사용됩니다. MyFirebaseMessagingService.java 이름

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); 

    @Override 
    public void onTokenRefresh() { 
     super.onTokenRefresh(); 
     String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 

     // Saving reg id to shared preferences 
     storeRegIdInPref(refreshedToken); 

     // sending reg id to your server 
     sendRegistrationToServer(refreshedToken); 

     // Notify UI that registration has completed, so the progress indicator can be hidden. 
     Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); 
     registrationComplete.putExtra("token", refreshedToken); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 
    } 

    private void sendRegistrationToServer(final String token) { 
     // sending gcm token to server 
     Log.e(TAG, "sendRegistrationToServer: " + token); 
    } 

    private void storeRegIdInPref(String token) { 
    SharedPreferences pref =  getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); 
     SharedPreferences.Editor editor = pref.edit(); 
     editor.putString("regId", token); 
     editor.commit(); 
    } 
    } 

7.Create 하나 개 이상의 서비스 클래스입니다. 이것은 firebase 메시지를 받게됩니다. AndroidManifest.xml을 8.In

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); 

    private NotificationUtils notificationUtils; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     Log.e(TAG, "From: " + remoteMessage.getFrom()); 

     if (remoteMessage == null) 
      return; 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); 
      handleNotification(remoteMessage.getNotification().getBody()); 
     } 
    } 
private void handleNotification(String message) { 
     if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 
      // app is in foreground, broadcast the push message 
      Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); 
      pushNotification.putExtra("message", message); 
      LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 

      // play notification sound 
      NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 
      notificationUtils.playNotificationSound(); 
     }else{ 
      // If the app is in background, firebase itself handles the notification 
     } 
    } 
/** 
    * Showing notification with text only 
    */ 
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent); 
    } 

    /** 
    * Showing notification with text and image 
    */ 
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { 
     notificationUtils = new NotificationUtils(context); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); 
    } 
} 

이 두 중포 기지 서비스 MyFirebaseMessagingService 및 MyFirebaseInstanceIDService를 추가합니다. 이제

<!-- Firebase Notifications --> 
     <service android:name=".service.MyFirebaseMessagingService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.MESSAGING_EVENT" /> 
      </intent-filter> 
     </service> 

     <service android:name=".service.MyFirebaseInstanceIDService"> 
      <intent-filter> 
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> 
      </intent-filter> 
     </service> 
     <!-- ./Firebase Notifications --> 

단순히 Send your First Message

참고 : Firebase Cloud Messaging *

에 대한

* 1.Read Google 문서 당신이를 마이그레이션 할 2.If Android 용 GCM 클라이언트 앱 전나무 EBASE 클라우드 메시징은 다음 단계 및 문서 (Migrate a GCM Client App)

3.Android 샘플 튜토리얼 및 코드 (Receive Reengagement Notifications)