안드로이드 gcm 푸시 서비스를 구현중에 있는데
아래의 샘플코드를 테스트 중에 확인해보니 스크린이 켜져있는 상태에서는
메시지를 받지만 스크린이 꺼지고 약 10초가량 뒤에는 리시버가 작동을 하지 않습니다.
WakefulBroadcastReceiver 객체를 상속받아서 처리하면 된다고 되어 있는데 도저히 해결이 되질 않네요.
아시는분 도움좀 부탁드립니다.
감사합니다.
GcmBroadcastReceiver.java
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
GcmMessageHandler.java
public class GcmMessageHandler extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
String mes;
private Handler handler;
public GcmMessageHandler() {
super("GcmMessageHandler");
}
public void onCreate() {
super.onCreate();
handler = new Handler();
}
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
sendNotification("Received: " + extras.toString());
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button btnRegId;
EditText etRegId;
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = "프로젝트 번호";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegId = (Button) findViewById(R.id.btnGetRegId);
etRegId = (EditText) findViewById(R.id.etRegId);
btnRegId.setOnClickListener(this);
}
public void getRegId(){
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID=" + regid;
} catch (IOException ex) {
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
etRegId.setText(msg + "\n");
}
}.execute(null, null, null);
}
public void onClick(View v) {
getRegId();
}
}