2014년 8월 12일 화요일

Google Cloud Messaging (GCM) in Android using PHP Server

RegisterApp.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.programmingtechniques.gcmdemo;
  
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
  
  
public class RegisterApp extends AsyncTask<Void, Void, String> {
  
 private static final String TAG = "GCMRelated";
 Context ctx;
 GoogleCloudMessaging gcm;
 String SENDER_ID = "343594554298";
 String regid = null
 private int appVersion;
 public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
  this.ctx = ctx;
  this.gcm = gcm;
  this.appVersion = appVersion;
 }
   
   
 @Override
 protected void onPreExecute() {
  super.onPreExecute();
 }
  
  
 @Override
 protected String doInBackground(Void... arg0) {
  String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(ctx);
            }
            regid = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regid;
  
            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();
  
            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.
  
            // Persist the regID - no need to register again.
            storeRegistrationId(ctx, regid);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
        }
        return msg;
 }
  
 private void storeRegistrationId(Context ctx, String regid) {
  final SharedPreferences prefs = ctx.getSharedPreferences(MainActivity.class.getSimpleName(),
             Context.MODE_PRIVATE);
     Log.i(TAG, "Saving regId on app version " + appVersion);
     SharedPreferences.Editor editor = prefs.edit();
     editor.putString("registration_id", regid);
     editor.putInt("appVersion", appVersion);
     editor.commit();
    
 }
  
  
 private void sendRegistrationIdToBackend() {
  URI url = null;
  try {
   url = new URI("http://10.0.2.2/GCMDemo/register.php?regId=" + regid);
  } catch (URISyntaxException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  
  HttpClient httpclient = new DefaultHttpClient();
  HttpGet request = new HttpGet();
  request.setURI(url);
  try {
   httpclient.execute(request);
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
  
  
 @Override
 protected void onPostExecute(String result) {
  super.onPostExecute(result);
  Toast.makeText(ctx, "Registration Completed. Now you can see the notifications", Toast.LENGTH_SHORT).show();
  Log.v(TAG, result);
 }
}

MainActivity.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package com.programmingtechniques.gcmdemo;
  
import java.util.concurrent.atomic.AtomicInteger;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
  
public class MainActivity extends Activity {
   
 private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
 public static final String EXTRA_MESSAGE = "message";
 public static final String PROPERTY_REG_ID = "registration_id";
 private static final String PROPERTY_APP_VERSION = "appVersion";
 private static final String TAG = "GCMRelated";
 GoogleCloudMessaging gcm;
 AtomicInteger msgId = new AtomicInteger();
 String regid;
  
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  final Button button = (Button) findViewById(R.id.register);
    
  if (checkPlayServices()) {
      gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
            regid = getRegistrationId(getApplicationContext());
            if(!regid.isEmpty()){
             button.setEnabled(false);
            }else{
             button.setEnabled(true);
            }
  }
    
  button.setOnClickListener(new View.OnClickListener() {
     
   @Override
   public void onClick(View view) {
    // Check device for Play Services APK.
       if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
              regid = getRegistrationId(getApplicationContext());
                
              if (regid.isEmpty()) {
               button.setEnabled(false);
                  new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
              }else{
               Toast.makeText(getApplicationContext(), "Device already Registered", Toast.LENGTH_SHORT).show();
              }
       } else {
              Log.i(TAG, "No valid Google Play Services APK found.");
       }
   }
  });
    
    
 }
  
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
   
 /**
  * Check the device to make sure it has the Google Play Services APK. If
  * it doesn't, display a dialog that allows users to download the APK from
  * the Google Play Store or enable it in the device's system settings.
  */
   
 private boolean checkPlayServices() {
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
     if (resultCode != ConnectionResult.SUCCESS) {
         if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
             GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                     PLAY_SERVICES_RESOLUTION_REQUEST).show();
         } else {
             Log.i(TAG, "This device is not supported.");
             finish();
         }
         return false;
     }
     return true;
 }
   
 /**
  * Gets the current registration ID for application on GCM service.
  * <p>
  * If result is empty, the app needs to register.
  *
  * @return registration ID, or empty string if there is no existing
  *         registration ID.
  */
 private String getRegistrationId(Context context) {
     final SharedPreferences prefs = getGCMPreferences(context);
     String registrationId = prefs.getString(PROPERTY_REG_ID, "");
     if (registrationId.isEmpty()) {
         Log.i(TAG, "Registration not found.");
         return "";
     }
     // Check if app was updated; if so, it must clear the registration ID
     // since the existing regID is not guaranteed to work with the new
     // app version.
     int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
     int currentVersion = getAppVersion(getApplicationContext());
     if (registeredVersion != currentVersion) {
         Log.i(TAG, "App version changed.");
         return "";
     }
     return registrationId;
 }
   
 /**
  * @return Application's {@code SharedPreferences}.
  */
 private SharedPreferences getGCMPreferences(Context context) {
  // This sample app persists the registration ID in shared preferences, but
     // how you store the regID in your app is up to you.
     return getSharedPreferences(MainActivity.class.getSimpleName(),
             Context.MODE_PRIVATE);
 }
   
 /**
  * @return Application's version code from the {@code PackageManager}.
  */
 private static int getAppVersion(Context context) {
     try {
         PackageInfo packageInfo = context.getPackageManager()
                 .getPackageInfo(context.getPackageName(), 0);
         return packageInfo.versionCode;
     } catch (NameNotFoundException e) {
         // should never happen
         throw new RuntimeException("Could not get package name: " + e);
     }
 }
}
When you run the above android application, it displays a layout with a simple button. After clicking the button, the application checks whether it has registration id or not. If not then the application registers the device in background. Once it gets the registration id, it sends that Id to the application server to store in the database.

The application now can receive the messages sent by the application server. Whenever it sense the new message, then it pushes the message as a notification using notification manager.

댓글 없음:

댓글 쓰기