Showing posts with label GCM. Show all posts
Showing posts with label GCM. Show all posts

Tuesday, 14 August 2018

HB Blog 158: Jetpack Architecture: - Work Manager.

The WorkManager API makes it easy to specify deferrable, asynchronous tasks and when they should run. These APIs let you create a task and hand it off to WorkManager to run immediately or at an appropriate time.

It is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.

It chooses an appropriate way to schedule a background task--depending on the device API level and included dependencies, which might use JobScheduler, Firebase JobDispatcher, or AlarmManager. You don't need to write device logic to figure out what capabilities the device has and choose an appropriate API; instead, you can just hand your task off to WorkManager and let it choose the best option.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
1
2
3
4
5
6
7
8
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    def work_version = "1.0.0-alpha04"
    implementation "android.arch.work:work-runtime:$work_version" // use -ktx for Kotlin
    // optional - Firebase JobDispatcher support
    implementation "android.arch.work:work-firebase:$work_version"
}

//BasicWorker.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.harshalbenake.workmanager.worker;

import android.support.annotation.NonNull;
import androidx.work.Worker;

public class BasicWorker extends Worker{

    @Override
    public Result doWork() {
        printBasicWork();
        // Indicate success or failure with your return value:
        return Result.SUCCESS;
    }

    private void printBasicWork() {
        System.out.println("harshalbenake printBasicWork");
    }
}

//PeriodicWorker.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.harshalbenake.workmanager.worker;

import android.support.annotation.NonNull;
import androidx.work.Worker;

public class PeriodicWorker extends Worker{
 
    @Override
    public Result doWork() {
        printPeriodicWork();
        // Indicate success or failure with your return value:
        return Result.SUCCESS;
    }

    private void printPeriodicWork() {
        System.out.println("harshalbenake printPeriodicWork");
    }
}

Thursday, 22 October 2015

HB Blog 99: How To Integrate Urban Airship - Push Notification In Android And iOS???

Urban Airship is an American mobile technology company. It provides tools and services designed for mobile application developers to easily enhance their applications with audience engagement services, such as push notifications and integrated rich text notifications and in-app pages. Urban Airship primarily provides app developers the ability to easily add features such as creation and delivery of enhanced push notifications and a digital wallet, as well as reporting on the use of those features back to app developers. The company offers these services on Android, iOS, etc.
How to integrate Urban Airship push notification in Android: -

Add the SDK to your project in Android Studio: -
  1. Open your project in Android Studio
  2. Modify your application’s build.gradle script to include the Urban Airship Android Maven repository and dependencies:
  3.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    repositories {
        jcenter()
    
        maven {
            url  "http://dl.bintray.com/urbanairship/android"
        }
    }
    
    dependencies {
        // Urban Airship SDK
        compile 'com.urbanairship.android:urbanairship-sdk:6.1.+'
    
        // Recommended for in-app messaging
        compile 'com.android.support:cardview-v7:22.2.0'
    
        // Recommended for location services
        compile 'com.google.android.gms:play-services-location:7.5.0'
    
        // Required for Android (GCM) push notifications
        compile 'com.google.android.gms:play-services-gcm:7.5.0'
    }
    
  4. Sync the project with the gradle file.
Add the following permissions in Android Manifest: -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!-- REQUIRED for Urban Airship -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />  <!-- Required for Push -->

<permission android:name="${applicationId}.permission.UA_DATA" android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.UA_DATA" />
<!-- The two elements above ensure that only this application has access to the Urban Airship provider -->

<!-- OPTIONAL Urban Airship Settings -->
<!-- REQUIRED FOR LOCATION -->
<!-- Use ACCESS_COARSE_LOCATION if GPS access is not necessary -->
<!-- uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


Add the following services, provider, receivers, and activities under the application tag: -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!-- REQUIRED for Action.startActivityForResult -->
<activity android:name="com.urbanairship.actions.ActionActivity" />

<!-- REQUIRED for Urban Airship Push -->
<activity android:name="com.urbanairship.CoreActivity" />

<!-- REQUIRED for Urban Airship Push. The priority is important to be set lower than the
application's push intent receiver in order for the push intent receiver to handle push intents
before the core receiver. This allows the application to launch any activities before Urban
Airship performs any actions or falls back to launching the application launch intent. -->
<receiver android:name="com.urbanairship.CoreReceiver"
          android:exported="false">

    <intent-filter android:priority="-999">
        <action android:name="com.urbanairship.push.OPENED" />
        <category android:name="${applicationId}" />
    </intent-filter>
</receiver>

<!-- REQUIRED for Landing Pages
    - For more customization details, see com.urbanairship.actions.LandingPageActivity -->
<activity
    android:name="com.urbanairship.actions.LandingPageActivity"
    android:exported="false">

    <intent-filter>
        <action android:name="com.urbanairship.actions.SHOW_LANDING_PAGE_INTENT_ACTION" />

        <data android:scheme="http" />
        <data android:scheme="https" />
        <data android:scheme="message" />

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

<!-- REQUIRED for Urban Airship -->
<service android:name="com.urbanairship.push.PushService" android:label="Push Notification Service" />

<!-- Required for analytics -->
<service android:name="com.urbanairship.analytics.EventService" android:label="Event Service" />

<!-- Required for Actions -->
<service android:name="com.urbanairship.actions.ActionService" />

<!-- Required for Rich Push -->
<service android:name="com.urbanairship.richpush.RichPushUpdateService" />

<!-- OPTIONAL for Urban Airship Location (for segments support) -->
<service android:name="com.urbanairship.location.LocationService" android:label="Segments Service" />

<!-- This is required for persisting preferences related to push and location -->
<provider
    android:name="com.urbanairship.UrbanAirshipProvider"
    android:authorities="${applicationId}.urbanairship.provider"
    android:permission="${applicationId}.permission.UA_DATA"
    android:exported="true"
    android:multiprocess="true" />


Create a new airshipconfig.properties file with your application’s settings: -
developmentAppKey = Your Development App Key
developmentAppSecret = Your Development App Secret
productionAppKey = Your Production App Key
productionAppSecret = Your Production Secret
# Toggles between the development and production app credentials
# Before submitting your application to an app store set to true
inProduction = false
# LogLevel is "VERBOSE", "DEBUG", "INFO", "WARN", "ERROR" or "ASSERT"
developmentLogLevel = DEBUG
productionLogLevel = ERROR


Starting Urban Airship Services: -
The Urban Airship SDK requires only a single entry point in the application, known as takeOff. To start, create a class that extends Application and set the name of the class for the application entry in the AndroidManifest.xml:
1
<application android:name=".CustomApplication" ... />

Then, override the application’s onCreate to call UAirship.takeOff:
1
2
3
4
@Override
public void onCreate() {
    UAirship.takeOff(this);
}

This will bootstrap the SDK and look for the settings in airshipconfig.properties. These can also optionally be provided at run time by passing an AirshipConfigOptions in the call to UAirship.takeOff:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Override
public void onCreate() {
    AirshipConfigOptions options = new AirshipConfigOptions();
    options.developmentAppKey = "Your Development App Key";
    options.developmentAppSecret = "Your Development App Secret";
    options.productionAppKey = "Your Production App Key";
    options.productionAppSecret = "Your Production App Secret";
    options.inProduction = false;
    UAirship.takeOff(this, options);
}

Enabling User Notifications :-
The Channel ID is a unique identifier that ties together an application/device pair on Android and Amazon devices. The Channel ID is used to target pushes to specific devices using the Urban Airship API. Once a Channel ID is created, it will persist the application until it is either reinstalled, or its internal data is cleared. The Channel ID will be logged for all apps. You can always get the Channel ID with a couple of extra lines to your application.
The Urban Airship SDK makes a distinction between “user notifications”, which can be seen by the user, and other forms of push that allow you to send data to your app silently, or in the background. Enabling or disabling user notifications is a preference often best left up to the user, so by default, user notifications are disabled. For testing purposes, enabling notification at startup requires a few extra lines of code to your main application class.
After UAirship.takeOff, call:
1
2
3
String channelId = UAirship.shared().getPushManager().getChannelId();
Logger.info("My Application Channel ID: " + channelId);
UAirship.shared().getPushManager().setUserNotificationsEnabled(true);

How to integrate Urban Airship push notification in iOS: -
Download and unzip the latest version of libUAirship into the same directory as your project. You should see a new directory, named Airship, containing the latest version of the libUAirship static library and headers, as well as an AirshipKit directory, containing an Xcode project that builds the AirshipKit embedded framework.
Before you begin, make sure both the AirshipKit and Airship directories are in the top level of your app’s source directory.
  1. Include AirshipKit as a project dependency - Drag AirshipKit.xcodeproj out of the AirshipKit folder and into your app project in Xcode (directly under the top level of the project structure). Now AirshipKit will be built at compile-time for the active architecture.
  2. Link against the embedded framework - To link against the embedded framework, add the AirshipKit.framework file to the Embedded Binaries section in the General tab for your target. This should also add it to the Linked Frameworks and Libraries section.
  3. Check Linked Frameworks and Libraries - Make sure AirshipKit.framework shows up in the Linked Frameworks and Libraries section in the General tab for your target.
Create AirshipConfig.plist: -
The Urban Airship SDK uses a .plist configuration file named AirshipConfig.plist to manage your production and development application profiles.
  1.     Create two applications within your Urban Airship account: One for development and one for production.
  2.     Create an AirshipConfig.plist file.
  3.     Set the following values to the ones in your applications
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>inProduction</key>
  <false/>
  <key>developmentAppKey</key>
  <string>Your Development App Key</string>
  <key>developmentAppSecret</key>
  <string>Your Development App Secret</string>
  <key>productionAppKey</key>
  <string>Your Production App Key</string>
  <key>productionAppSecret</key>
  <string>Your Production App Secret</string>
</dict>
</plist>

Starting Urban Airship Services: -
The Urban Airship SDK requires only a single entry point in the app delegate, known as takeOff. Inside your application delegate’s application:didFinishLaunchingWithOptions: method, initialize a shared UAirship instance by calling [UAirship takeOff]. This will bootstrap the SDK and look for settings specified in the AirshipConfig.plist file you created earlier.

Import the Required Header Files: -
1
2
3
4
5
#import "UAirship.h"
#import "UAConfig.h"
#import "UAPush.h"
#import <AirshipKit/AirshipKit.h>
@import AirshipKit;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Populate AirshipConfig.plist with your app's info from https://go.urbanairship.com
    // or set runtime properties here.
    UAConfig *config = [UAConfig defaultConfig];
    // You can also programmatically override the plist values:
    // config.developmentAppKey = @"YourKey";
    // etc.
    // Call takeOff (which creates the UAirship singleton)
    [UAirship takeOff:config];
}
//Retrieving your Channel ID
//The Channel ID is a unique identifier that ties together an application/device pair on iOS devices. The Channel ID is used to target pushes to specific devices using the Urban Airship API.
NSString *channelId = [UAirship push].channelID;
NSLog(@"My Application Channel ID: %@", channelId);

    

Enabling User Notifications:-
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Set the notification types required for the app (optional). This value defaults
// to badge, alert and sound, so it's only necessary to set it if you want
// to add or remove types.
[UAirship push].userNotificationTypes = (UIUserNotificationTypeAlert |
                                         UIUserNotificationTypeBadge |
                                         UIUserNotificationTypeSound);

//To enable user notifications programmatically
// User notifications will not be enabled until userPushNotificationsEnabled is
// set YES on UAPush. Once enabled, the setting will be persisted and the user
// will be prompted to allow notifications. Normally, you should wait for a more appropriate
// time to enable push to increase the likelihood that the user will accept
// notifications.
[UAirship push].userPushNotificationsEnabled = YES;

Tuesday, 16 December 2014

HB Blog 43: Google Cloud Messaging (GCM) Client Integration For Android Devices.

Google Cloud Messaging (GCM) for Android is a service that allows you to send data from your server to your users' Android-powered device, and also to receive messages from devices on the same connection.A Google Cloud Messaging (GCM) client is a GCM-enabled app that runs on an Android device. A full GCM implementation requires both a client implementation and a server implementation.

In this blog post, I would talk about a Google Cloud Messaging (GCM) client implementation specifically.

A GCM implementation includes a Google-provided connection server, a 3rd-party app server that interacts with the connection server, and a GCM-enabled client app running on an Android device.

The steps involved in writing a GCM client-side application are as follows:
1)Set up Google Play Services using its SDK.
2)Add the following to your application's manifest:
   a)Android permissions related to Internet, register and receive messages, Google account, wake lock, GCM Framework, etc. 
   b)A receiver for com.google.android.c2dm.intent.RECEIVE.
   c)A Service (typically an IntentService) to which the WakefulBroadcastReceiver passes off the work of handling the GCM message.
3)Finally, write your application code for checking Google Play Services APK, register for GCM, send a message, receive a message, etc.

I have added a sample example in this post that implements GCM client services by sending device information as well as gcm notification id to the server and in return server will send message which will be displayed in form of notification on client device.

Have a look on few code snippets,
GCMIntentService.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class GCMIntentService extends GCMBaseIntentService {
    String TAG="GCM";
    @Override
    protected void onError(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onError() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }
    }

    @Override
    protected void onMessage(Context context, Intent intent) {
 try {
     String action = intent.getAction();
     Log.v(TAG, "onMessage() "+action);
     if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
  Log.v(TAG,"Handle Registration");
     } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
  Log.v(TAG,"intent.getExtras() "+intent.getExtras());

  /**Show notification.*/
  String messageText= intent.getStringExtra("message")+"";
  NotificationManagerGCM notificationManagerGCM=new NotificationManagerGCM();
  if(messageText!=null && !messageText.equalsIgnoreCase("") && !messageText.equalsIgnoreCase("null"))
  {
      notificationManagerGCM.showNotificationRemoveableGCM(context,messageText);
  }
  else
  {
      notificationManagerGCM.showNotificationRemoveableGCM(context,"Notification Message GCM Demo");
  }
     }
 } 
 catch (Exception e) {
     e.printStackTrace();
 }
    }

    @Override
    protected void onRegistered(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onRegistered() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }

    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
 try {
     Log.v(TAG, "onUnregistered() "+arg1);
 } catch (Exception e) {
     e.printStackTrace();
 }

    }

    @Override
    protected String[] getSenderIds(Context context) {
 String[] ids = new String[1];
 NotificationManagerGCM managerTXTShield=new NotificationManagerGCM();
 ids[0] = managerTXTShield.getGCMSenderID(context);
 return ids;
    }

}

AccountManager.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class AccountManager
{
    Context mContext;
    Resources mResources;
    String url,apiKey;

    public AccountManager(Context mContext){
 this.mContext = mContext;
 mResources = mContext.getResources();
 url = mContext.getResources().getString(R.string.url);
 apiKey = mContext.getResources().getString(R.string.api_key);

    }

    /**
     * This method is used to send device information for gcm notification.
     * 
     * @param context
     * @param user_id
     * @return
     */
    public String requestDeviceRegistration(Context context)
    {
 String responseStr = "";
 try{
     // Create a new HttpClient and Post Header
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost(url);
     try{
  Utility utility = new Utility();
  String unique_device_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
  if(unique_device_id == null || unique_device_id.equalsIgnoreCase("null") || unique_device_id.equalsIgnoreCase("")){
      unique_device_id = utility.getDeviceSerialNumber();
  }
  String device_name = utility.getDeviceName();
  String model_no = utility.getDeviceModelName();
  String device_os_version = utility.getDeviceSDKVersion();
  String notification_id = utility.getNotificationID(context);    
  PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
  String app_version = pInfo.versionName;

  System.out.println("apiKey: "+apiKey);
  System.out.println("unique_device_id: "+unique_device_id);
  System.out.println("notification_id: " + notification_id);
  System.out.println("device_name: "+device_name);
  System.out.println("model_no: "+model_no);
  System.out.println("device_os_version: "+device_os_version);
  System.out.println("app_version: "+app_version);


  // Add your data
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
  nameValuePairs.add(new BasicNameValuePair("unique_device_id", unique_device_id));
  nameValuePairs.add(new BasicNameValuePair("notification_id", notification_id));
  nameValuePairs.add(new BasicNameValuePair("device_name", device_name));
  nameValuePairs.add(new BasicNameValuePair("model_no", model_no));
  nameValuePairs.add(new BasicNameValuePair("device_os_version", device_os_version));
  nameValuePairs.add(new BasicNameValuePair("app_version", app_version));

  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

  // Execute HTTP Post Request
  HttpResponse httpResponse = httpclient.execute(httppost);

  HttpEntity responseEntity = httpResponse.getEntity();
  if(responseEntity != null){
      responseStr = EntityUtils.toString(responseEntity);
  }
     }
     catch(Exception e){
  e.printStackTrace();
     }
 }
 catch(Exception e){
     e.printStackTrace();
 }
 return responseStr;
    }
}

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File