0

알림의 텍스트를 클립 보드에 복사 할 수있는 버튼이 필요합니다. 알림은 Google의 GCM 서비스를 통해 전송됩니다.Android - 알림의 작업 버튼에서 서비스를 호출하는 데 문제가 있습니다.

"복사"버튼을 누를 때 처음 알림이 도착하면 버튼이 의도를 전송하는 서비스에 의해 모든 것이 정상이며 텍스트가 클립 보드로 들어갑니다. "복사"버튼을 누르면 두 번째 알림이 다른 텍스트와 함께 도착합니다. 첫 번째 알림의 내용은 새 알림 대신 클립 보드에 저장됩니다. 코드를 디버깅 할 때 서비스를 호출하는 의도가 새로운 내용을 가지고있는 것처럼 보이지만 클립 보드에 넣는 서비스는 이전 알림의 매개 변수로 실행됩니다. 마치 서비스의 동일한 세션이 늙은 의도.

이 현상이 발생하는 이유는 무엇입니까?

// Called by the GCM notification handler 

private void sendNotification(String msg) { 
    mNotificationManager = (NotificationManager) 
      this.getSystemService(Context.NOTIFICATION_SERVICE); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0); 
    Intent notificationIntent = new Intent(this, clipboardService.class); 
    notificationIntent.putExtra("tool",msg); 
    PendingIntent serviceIntent = PendingIntent.getService(this, 0, notificationIntent, 0); 

    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.ic_stat_gcm) 
        .setContentTitle("Here's your text!") 
        .setStyle(new NotificationCompat.BigTextStyle() 
          .bigText(msg)) 
        .setContentText(msg) 
        .addAction(R.drawable.ic_stat_gcm, "Copy", serviceIntent); // <--- The intent will have the right (new) value on the second run 
    mBuilder.setContentIntent(contentIntent); 
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
} 

알림 조치를 호출하는 서비스로 :

public class clipboardService extends IntentService { 
public clipboardService() { 
    super("clipboardService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { //This intent will have the values of the first intent to fire, instead of the updated one. 
    String msg = (String) intent.getExtras().get("tool"); 
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    ClipData clip = ClipData.newPlainText("2android",msg); 
    clipboard.setPrimaryClip(clip); 
} 

답변

0

가 귀하의 질문에 대답하는 것은 매우 늦게이지만, 그러나 최근에 나는 동일한 문제에 직면하고 구글이 나에게이 답이없는 질문을 주도 . 그래서 미래에 누군가가 이것을 파헤 치면 내 이해가 있습니다.

PendingIntent은 명시 적으로 지정하지 않는 한 인 텐트의 이전 인스턴스에서 캐시 된 인 텐트 엑스트라를 사용하기 때문입니다. 플래그와 (귀하의 경우 최고)

  1. 사용 FLAG_CANCEL_CURRENT 또는 FLAG_UPDATE_CURRENTPendingIntent를 구축 할 것을 두 가지 방법이 ...있다. 첫 번째 플래그는 이전의 PendingIntent을 자동으로 닫고 완전히 새로운 플래그를 만들고 두 번째 플래그는 PendingIntent의 추가 항목 만 업데이트하고 완전히 새로운 플래그를 생성하는 오버 헤드를 저장합니다.

    PendingIntent.getService(this, 0, notificationIntent, 
             FLAG_CANCEL_CURRENT | FLAG_UPDATE_CURRENT); 
    
  2. PendingIntent 생성자 매번에 고유 requestCode을 전달합니다. 이렇게하면 매번 고유 한 보류중인 인 텐트가 생성되므로 나중에 특정 인 텐트와 관련된 엑스트라에 액세스 할 수 있습니다. 나는 이것이 귀하의 경우에는 필요하지 않습니다 믿습니다.

    PendingIntent.getService(this, UNIQUE_ID, pi, 0);