воскресенье, 11 ноября 2012 г.

Android Push Notification for PhoneGap

PUSH уведомления в андроиде с помощью phonegap

по результатам работы с сервисом pushwoosh я остался ужасно недоволен его возможностями и для использования технологии PUSH на андроиде написао свой плагин.

Великолепная возможность предоставляемая смартфонами - напоминание приложения о себе через постоянное показывание сообщений, поступающих на приложение из внешнего мира.

Здесь будет рассмотрена реализация PUSH-технологии в phonegap с помощью PushWoosh.

Англоязычный оригинал статьи здесь.

Кроме прочтения информации об архитектуре этой службы нужно ещё

Чтобы интегрировать Pushwoosh в наше PhoneGap приложение нужно сделать сделать следующие простые шаги:

1. Получить кода плагина для Android с https://github.com/shaders/phonegap-cordova-push-notifications/tree/master/Android
2. Скопировать папку “src” в наш проект.
2.a Скопировать файл Pushwoosh.jar в папку “libs” и добавить его в classpath проекта.
Для Eclipse: http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
Для IDEA: http://stackoverflow.com/questions/1051640/correct-way-to-add-lib-jar-to-an-intellij-idea-project
3. Добавить PushNotification.js из папки www в нашу папку www на диске
4. Добавить ссылку на файл PushNotification.js используя тэги <script> в нашем html-файле:
<script type="text/javascript" src="PushNotification.js"></script>
5. Добавить новую строку о плагине в файл “res/xml/config.xml” (Для версий кордова Cordova < 2.0 нужно добавить эту строку в plugins.xml.)
<plugins>
    <plugin name="PushNotification" value="com.pushwoosh.test.plugin.pushnotifications.PushNotifications" onload="true"/>

Добавить новую строку в “cordova.xml” (если у нас нет cordova.xml, нужно добавить эту строку в res/xml/config.xml)

<cordova>

    <access origin="https://cp.pushwoosh.com" subdomains="true" />


6. Регистрируемся для push уведомлений:
Добааляем следующую функцию в наш javascript-файл, вводим соответсвующие Project ID  и Pushwoosh App ID, которые быти упомянуты в преамбуле
function initPushwoosh()
{
    var pushNotification = window.plugins.pushNotification;
    pushNotification.registerDevice({ projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID" },
        function(status) {
            var pushToken = status;
            console.warn('push token: ' + pushToken);
        },
        function(status) {
            console.warn(JSON.stringify(['failed to register ', status]));
        }
    );
    document.addEventListener('push-notification', function(event) {
        var title = event.notification.title;
            var userData = event.notification.userdata;
            if(typeof(userData) != "undefined") {
            console.warn('user data: ' + JSON.stringify(userData));
        }
        navigator.notification.alert(title);
    });
}

Добавим метод init() в функцию onload в HTML:
<body onload="init();" >

и добавим саму функцию init():

function init() {

    document.addEventListener("deviceready", initPushwoosh, true);


    //rest of the code

}


Если вам нужна регистрация PUSH не при запуске приложения, а позже, исправьте код под свои нужды.

7. Получение push уведомлений. Смотрите следующий кусок кода в функции initPushwoosh

  document.addEventListener('push-notification', function(event) {

        var title = event.notification.title;

            var userData = event.notification.userdata;


        console.warn('user data: ' + JSON.stringify(userData));

        navigator.notification.alert(title);
});

8. Добавляем следдующие изменеия в наш AndroidManifest.xml под тэгом manifest. Заменяем PACKAGE_NAME именем пакета приложения. (Имя пакета можно найти в AndroidManifest.xml под тэгом manifest в самом верху файла.)

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <!--library-->
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <!-- 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"/>
 <!--
  Creates a custom permission so only this app can receive its messages.
  NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
        where PACKAGE is the application's package name.
 -->
 <permission
         android:name="PACKAGE_NAME.permission.C2D_MESSAGE"
         android:protectionLevel="signature"/>
 <uses-permission
         android:name="PACKAGE_NAME.permission.C2D_MESSAGE"/>
 <!-- This app has permission to register and receive data message. -->
 <uses-permission
         android:name="com.google.android.c2dm.permission.RECEIVE"/>
 <!-- GCM requires Android SDK version 2.2 (API level <img src="http://www.pushwoosh.com/wp-includes/images/smilies/icon_cool.gif" alt="8)" class="wp-smiley"> or above. -->
 <!-- The targetSdkVersion is optional, but it's always a good practice
      to target higher versions. -->
 <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>

9. Добавляем следующие изменения в AndroidManifest.xml в теге application. Заменяем PACKAGE_NAME именем пакета приложения. (Имя пакета можно найти в AndroidManifest.xml под тэгом manifest в самом верху файла.)
<activity android:name="com.arellomobile.android.push.PushWebview"/>
<activity android:name="com.arellomobile.android.push.MessageActivity"/>
<activity android:name="com.arellomobile.android.push.PushHandlerActivity"/>
<!--
  BroadcastReceiver that will receive intents from GCM
  services and handle them to the custom IntentService.
  The com.google.android.c2dm.permission.SEND permission is necessary
  so only GCM services can send data messages for the app.
-->
<receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <!-- Receives the actual messages. -->
        <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
        <!-- Receives the registration id. -->
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
        <category android:name="PACKAGE_NAME"/>
    </intent-filter>
</receiver>
<!--
  Application-specific subclass of PushGCMIntentService that will
  handle received messages.
-->
<service android:name="com.arellomobile.android.push.PushGCMIntentService"/>


10. Добавляем следующие ищзменения в AndroidManifest.xml в тэге start activity.

<activity android:name="YourStartActivity"
           android:label="@string/app_name"
           android:configChanges="orientation|keyboardHidden"
           android:launchMode="singleTop"
         >
     <intent-filter>
         <action android:name="PACKAGE_NAME.MESSAGE"/>
         <category android:name="android.intent.category.DEFAULT"/>
     </intent-filter>
     <intent-filter>
         <action android:name="android.intent.action.MAIN"/>
         <category android:name="android.intent.category.LAUNCHER"/>
     </intent-filter>
 </activity>
Для совместимости с Android 4 пожалуйста удостовертесь, что вы используете по крайней мере 11 версию Android API.
SDK будет работать на более старых устройствах.