일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 도전의 기회
- 보고싶은 내맘
- 김영근 올패스
- 흐린날의 낮술
- CentOS 6 설치 오류
- 슈퍼스타k 2016
- 퇴근버스 조민욱
- 그게 무슨 의미가 있니
- 짝사랑
- 센티멘탈
- rsnapshot
- HttpURLConnection
- 영구정지
- account ban
- 커피레이크
- 내 자신의 생각
- 해맑게 웃는 너
- 질투
- 넬 희망고문
- 사랑 그렇게 보내네 김영근
- COC
- #만취
- 3rd party software
- nmtui
- 가식의 껍데기
- 흘러가는대로
- 퇴근버스 슈퍼스타K 2016
- 지리산 소울 김영근
- i7-8700
- 적절한 타이밍
- Today
- Total
끄적거림들...
Android GCM 사용하기 (Push Message) 본문
Android 에서 Google Cloud Message (GCM) 를 이용하여 Push 를 보내는 예제
google developer site 에서 app 등록 하고 api_key 먼저 받아놓으시고!!
오타가 있을지도;;; 쿨럭; -_-;
# Activity 단에서 처리하는 코드
// define
private GoogleCloudMessaging gcm;
private String regId;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
//onCreate
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (regId.isEmpty()){
registerInBackground();
}
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServiceUtil.isGooglePlayServiceAvailable(this);
if (resultcode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.d(TAG, "Registration not found.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
// Activity Name
return getSharedPreferences(Activity.class.getSimpleName(), Context.MODE_PRIVATE);
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GCM_SERVER_ID); // ServerId
msg = "Device registered, registration Id = " + regId;
sendRegistrationIdToServer();
// TODO setDevicePreferences(regId);
} catch (IOException e) {
msg = e.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
Log.d(TAG, msg);
}
}.execute(null, null, null);
}
private void sendRegistrationIdToServer() {
// TODO register to server
}
# GCM BroadcastReceiver
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
# GCM Intent Service
public class GcmIntentService extends IntentService {
private NotificationManager mNotificationManager;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
setNotification("SEND_ERROR : " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
setNotification("DELETED_MESSAGE : " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
for (int i = 0; i < 5; i++) {
Log.d(TAG, "... " + (i+1) + "/5 @" + SystemClock.elapsedRealtime());
try{
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setNotification("Message Received : " + extras.toString());
}
}
GcmBroadcaseReceiver.completeWakefulIntent(intent);
}
}
private void setNotification(String msg) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATON_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, Activity.class), 0); // Activity name
Uri notiSound = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtongManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.app_icon).setTicker("title").setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle("title").setContentText("content")
.setLights(Color.RED, 500, 5000);
// Bigger Style (if big)
NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
style.setBigContentTitle("title");
style.setSummaryText("content");
style.bigPicture(bitmap)); // using bitmap
mBuilder.setStyle(style);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSound(pushSound);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
# AndroidManifest.xml
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.package.name.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.package.name.permission.C2D_MESSAGE" />
<application>
<receiver
android:name="com.dlto.topping.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.dlto.topping" />
</intent-filter>
</receiver>
<service android:name="com.dlto.topping.GcmIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
'Androiddd' 카테고리의 다른 글
Eclipse Neon 이 나왔다능;;; (0) | 2016.09.06 |
---|---|
Android manageQuery deprecated (0) | 2016.09.06 |
Android AsyncTask 로 JSON Object 받아오기 (0) | 2016.09.06 |
Google Market 으로 이동하기 (0) | 2016.09.05 |
Android VersionCode VersionName 확인하기 (0) | 2016.09.05 |