private static final String TAG = "GCM"; private static final String PASSWORD = "1111"; //자신의 Project ID 를 넣어주세요 private static final String SENDER_ID = "자신의 프로젝트 아이디";
private Button managerButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//GCM 등록여부
final String regId = GCMRegistrar.getRegistrationId(this);
//등록된 ID가 없으면 ID값을 얻어옵니다
if (regId.equals("") || regId == null) {
GCMRegistrar.register(this, SENDER_ID);
}else{
Log.w(TAG, "Already Registered : " + regId);
}
setInit();
}
private static final String TAG = "GCM";
private static final String INSERT_PAGE = "http://자신의 서버 아이피/insert_registration.php";
private static final String SENDER_ID = "자신의 프로젝트 아이디";
private GCMHttpConnect httpConnect = null;
private GCMHttpConnect.Request httpRequest = new GCMHttpConnect.Request() {
@Override
public void OnComplete() {
// TODO Auto-generated method stub
showToast();
}
};
public GCMIntentService() {
super(SENDER_ID);
}protected void onMessage(Context context, Intent intent) {
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
showMessage(context, intent);
}
}
protected void onError(Context context, String msg) {
// TODO Auto-generated method stub
Log.w(TAG, "onError!! " + msg);
}
protected void onRegistered(Context context, String regID) {
// TODO Auto-generated method stub
if(!regID.equals("") || regID != null){
Log.w(TAG, "onRegistered!! " + regID);
// 단일전송일때 주석처리
// insertRegistrationID(regID);
}
}
protected void onUnregistered(Context context, String regID) {
// TODO Auto-generated method stub
Log.w(TAG, "onUnregistered!! " + regID);
}
public void showToast(){
Toast.makeText(this, "RegID 등록 완료", Toast.LENGTH_LONG).show();
}
private void showMessage(Context context, Intent intent){
String title = intent.getStringExtra("title");
String msg = intent.getStringExtra("msg");
String ticker = intent.getStringExtra("ticker");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);
// 해당 어플을 실행하는 이벤트를 하고싶을 때 아래 주석을 풀어주세요
// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
// new Intent(context, 어플이 처음 시작되는 클래스명.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = ticker;
notification.when = System.currentTimeMillis();
notification.vibrate = new long[] { 500, 100, 500, 100 };
notification.sound = Uri.parse("/system/media/audio/notifications/20_Cloud.ogg");
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, title, msg, pendingIntent);
notificationManager.notify(0, notification);
}
public void insertRegistrationID(String id){
httpConnect = new GCMHttpConnect(INSERT_PAGE + "?regID=" + id, httpRequest);
httpConnect.start();
}
private Sender gcmSender; //GCM Sender
private Message gcmMessage; //GCM Message
private Result gcmResult; //GCM Result(단일 전송)
private MulticastResult gcmMultiResult; //GCM Multi Result(일괄 전송)
//일괄전송에 필요한 List 변수
private List<String> registrationIds = new ArrayList<String>();
//단일전송에 필요한 변수
private String registrationId = "이곳에 RegId를 입력하세요";
//DB에서 RegID를 가져오기 위해 만들어진 서버 페이지 주소
private static final String SELECT_PAGE = "http://자신의 서버 아이피/select_registration.php";
//파싱하기 위해 데이터를 담을 변수
private static String JSON = null;
//개발자 콘솔에서 발급받은 API Key
private static String API_KEY = "자신이 발급받은 API KEY를 입력하세요";
//메세지의 고유 ID(?)정도로 생각하면 됩니다. 메세지의 중복수신을 막기 위해 랜덤값을 지정합니다
private static String COLLAPSE_KEY = String.valueOf(Math.random() % 100 + 1);
//기기가 활성화 상태일 때 보여줄 것인지.
private static boolean DELAY_WHILE_IDLE = true;
//기기가 비활성화 상태일 때 GCM Storage에 보관되는 시간
private static int TIME_TO_LIVE = 3;
//메세지 전송 실패시 재시도할 횟수
private static int RETRY = 3;
private EditText pushTicker;
private EditText pushTitle;
private EditText pushMessage;
private TextView pushLength;
private Button pushShow;
private Button pushTrans;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_message);
setLayout();
// 단일전송시에는 주석처리
// getJson(SELECT_PAGE);
// 단일전송시에는 주석처리
// getToken();
}
public void setMessage(){
gcmSender = new Sender(API_KEY);
gcmMessage = new Message.Builder()
.collapseKey(COLLAPSE_KEY)
.delayWhileIdle(DELAY_WHILE_IDLE)
.timeToLive(TIME_TO_LIVE)
.addData("ticker", pushTicker.getText().toString())
.addData("title", pushTitle.getText().toString())
.addData("msg", pushMessage.getText().toString())
.build();
}
public void sendMessage(){
//일괄전송시에 사용
// try {
// gcmMultiResult = gcmSender.send(gcmMessage, registrationIds, RETRY);
// } catch (IOException e) {
// Log.w(TAG, "IOException " + e.getMessage());
// }
// Log.w(TAG, "getCanonicalIds : " + gcmMultiResult.getCanonicalIds() + "\n" +
// "getSuccess : " + gcmMultiResult.getSuccess() + "\n" +
// "getTotal : " + gcmMultiResult.getTotal() + "\n" +
// "getMulticastId : " + gcmMultiResult.getMulticastId());
//단일전송시에 사용
try {
gcmResult = gcmSender.send(gcmMessage, registrationId, RETRY);
} catch(IOException e) {
Log.w(TAG, "IOException " + e.getMessage());
}
Log.w(TAG, "getCanonicalIds : " + gcmResult.getCanonicalRegistrationId() + "\n" +
"getMessageId : " + gcmResult.getMessageId());
}



개발자 정보에 올리시면 됩니다^^