이슈

GCM 에서 메시지 수신처리를 아래와 같이 할 경우 토스트 메시지가 뜨지 않는다.

 

public class GCMIntentService extends GCMBaseIntentService {

 

@Override
protected void onMessage(Context context, Intent intent) {

 

Toast.makeText(getApplicationContext(), "메시지 도착", Toast.LENGTH_LONG).show();

 

}

 

}

 

 

 

해결

UI와 관련된 toast 메시지는 UIThread에서 호출되어야 한다. 하지만 GCM 리시버는 독립적인 intent service 에서 실행되므로 toast가 실행되지 않는다. 아래와 같이 핸들러를 통해서 처리할 수 있다.

 

 public class GCMIntentService extends GCMBaseIntentService {

 

Handler postHandler = new Handler();

 

@Override
protected void onMessage(Context context, Intent intent) {

 

postHandler.post( new Runnable() {


    public void run() {


        Toast.makeText(getApplicationContext(), "메시지 도착", Toast.LENGTH_LONG).show();

 

     }

 

}

}

}

 

 

 

특이사항

아래와 같이 Handler 변수를 MainActivity에 선언 할 경우 토스트 메시지가 뜨지 않는다. 하지만 이클립스를 통해서 실행시킨 후에 GCM 메시지를 보내면 보여진다. 차이점이 무엇일까? 이클립스를 통한 실행과 직접 실행의 차이점이 무엇일까?

 

public class MainActivity extends Activity {

 

public static final Handler postHandler = new Handler();

 

}

 

public class GCMIntentService extends GCMBaseIntentService {

 

@Override
protected void onMessage(Context context, Intent intent) {

 

MainActivity.postHandler.post( new Runnable() {

    public void run() {
        

Toast.makeText(getApplicationContext(), "메시지 도착", Toast.LENGTH_LONG).show();

 

}

}

}

}


Posted by great-artist
,