codememo

알림 클릭에서 활동으로 매개 변수를 보내는 방법은 무엇입니까?

tipmemo 2023. 9. 5. 20:32
반응형

알림 클릭에서 활동으로 매개 변수를 보내는 방법은 무엇입니까?

알림에서 활동에 매개 변수를 보내는 방법을 찾을 수 있습니다.

저는 알림을 만드는 서비스를 가지고 있습니다.아이템 를 들어, 활동할 수 .예를 들어, 내 활동이 특수 항목 세부 정보 보기를 로드하고 표시할 수 있도록 항목 ID를 가져옵니다.좀 더 구체적으로 말하면, 파일을 다운로드하는 중인데, 파일이 다운로드될 때 알림을 클릭하면 특수 모드에서 활동이 열립니다.사용하려고 했습니다.putExtra의도적으로, 하지만 추출할 수 없는 것 같아서, 제가 잘못하고 있는 것 같습니다.

알림을 생성하는 내 서비스의 코드:

        // construct the Notification object.
     final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());


    final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
    contentView.setImageViewResource(R.id.image, R.drawable.icon);
    contentView.setTextViewText(R.id.text, tickerText);
    contentView.setProgressBar(R.id.progress,100,0, false);
    notif.contentView = contentView;        

    Intent notificationIntent = new Intent(context, Main.class);
    notificationIntent.putExtra("item_id", "1001"); // <-- HERE I PUT THE EXTRA VALUE
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notif.contentIntent = contentIntent;

    nm.notify(id, notif);

알림에서 추가 매개 변수를 가져오려는 내 활동의 코드:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);


    Bundle extras = getIntent().getExtras();
    if(extras != null){
        Log.i( "dd","Extra:" + extras.getString("item_id") );
    }

여분은 항상 null이고 저는 제 로그에 아무것도 기록하지 않습니다.

그나저나.. 그..onCreate활동이 시작될 때만 실행됩니다. 활동이 이미 시작된 경우 추가 정보를 수집하여 받은 item_id에 따라 활동을 표시합니다.

아이디어 있어요?

이 가이드(알림 만들기)를 살펴보고 ApiDemos "StatusBarNotifications" 및 "NotificationDisplay" 샘플을 확인하십시오.

활동이 이미 실행 중인지 여부를 관리하는 데는 두 가지 방법이 있습니다.

  1. 활동을 시작할 때 FLAG_ACTIVE_SINGLE_TOP 플래그를 Entit에 추가한 다음 활동 클래스에서 NewIntent(Intent) 이벤트 핸들러에 구현합니다. 그러면 활동에 대해 호출된 새 의도에 액세스할 수 있습니다(getIntent(),이렇게 하면 항상 활동을 시작한 첫 번째 의도가 반환됩니다.

  2. 1번과 동일하지만 Entit에 플래그를 추가하는 대신 AndroidManifest.xml 활동에 "singleTop"을 추가해야 합니다.

의도적인 추가 기능을 사용하는 경우, 전화하는 것을 기억하십시오.PendingIntent.getActivity()깃발을 들고PendingIntent.FLAG_UPDATE_CURRENT그렇지 않으면 모든 통지에 대해 동일한 추가 정보가 재사용됩니다.

응용프로그램에서 메시지 알림을 표시하는 것과 유사한 문제가 발생했습니다.알림이 여러 개 있고 각 알림을 누르면 해당 알림 세부 정보가 보기 메시지 활동에 표시됩니다.저는 뷰 메시지 의도에서 동일한 추가 파라미터가 수신되고 있는 문제를 해결했습니다.

여기 이것을 고친 코드가 있습니다.알림 의도를 만들기 위한 코드입니다.

 Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
    notificationIntent.putExtra("NotificationMessage", notificationMessage);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);

메시지 활동 보기 코드입니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    onNewIntent(getIntent());
}

@Override
public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    if(extras != null){
        if(extras.containsKey("NotificationMessage"))
        {
            setContentView(R.layout.viewmain);
            // extract the extra-data in the Notification
            String msg = extras.getString("NotificationMessage");
            txtView = (TextView) findViewById(R.id.txtMessage);
            txtView.setText(msg);
        }
    }


}

조금 늦었을 수도 있지만, 이것 대신에:

public void onNewIntent(Intent intent){
    Bundle extras = intent.getExtras();
    Log.i( "dbg","onNewIntent");

    if(extras != null){
        Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
        Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));

    }
    mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}

사용:

Bundle extras = getIntent().getExtras();
if(extras !=null) {
    String value = extras.getString("keyName");
}

여기서 동일한 문제가 발생합니다.다른 요청 코드를 사용하여 해결하고, 알림과 동일한 ID를 사용하여 보류 중을 만듭니다.의도적입니다. 하지만 여전히 이것이 왜 이루어져야 하는지 모르겠습니다.

PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(**id**, notif);

일부 이메일 목록과 다른 포럼을 읽은 후 트릭이 의도에 고유한 데이터를 추가하는 것처럼 보인다는 것을 발견했습니다.

다음과 같이:

   Intent notificationIntent = new Intent(Main.this, Main.class);
   notificationIntent.putExtra("sport_id", "sport"+id);
   notificationIntent.putExtra("game_url", "gameURL"+id);

   notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime()))); 

나는 이것이 왜 필요한지 이해할 수 없습니다. 그것은 그것의 추가적인 것으로만 식별될 수 없는 의도와 관련이 있습니다.

저는 모든 것을 시도했지만 아무 것도 되지 않았습니다.

결국 다음과 같은 해결책을 생각해냈습니다.

Android 활동을 위한 1-in 매니페스트 추가:launchMode="singleTop"

2- 보류 중인 의도가 다음을 수행하도록 하는 동안 의도를 직접 사용하는 대신 번들을 사용합니다.putString() 또는 intent.putInt()

                    Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);

                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
                    bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
                    bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());

                    notificationIntent.putExtras(bundle);

                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                            Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
                            new Random().nextInt(), notificationIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT); 

Android Manifest.xml

launchMode="singleTop" 포함

<activity android:name=".MessagesDetailsActivity"
        android:launchMode="singleTop"
        android:excludeFromRecents="true"
        />

SMSReceiver.java

의도 및 보류 중 플래그 설정의도

Intent intent = new Intent(context, MessagesDetailsActivity.class);
    intent.putExtra("smsMsg", smsObject.getMsg());
    intent.putExtra("smsAddress", smsObject.getAddress());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

메시지 세부 정보활동.java

onResume() - 매번 호출되며 추가 정보를 로드합니다.

Intent intent = getIntent();
    String extraAddress = intent.getStringExtra("smsAddress");
    String extraBody = intent.getStringExtra("smsMsg");

도움이 되길 바랍니다. 스택 오버플로에 대한 다른 답변을 기반으로 했지만, 이것이 저에게 가장 효과적인 업데이트입니다.

이것은 쉽습니다. 이것은 사물을 이용한 저의 해결책입니다!

나의 POJO

public class Person implements Serializable{

    private String name;
    private int age;

    //get & set

}

메서드 알림

  Person person = new Person();
  person.setName("david hackro");
  person.setAge(10);

    Intent notificationIntent = new Intent(this, Person.class);
    notificationIntent.putExtra("person",person);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.notification_icon)
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
                .setPriority(2)
                .setLargeIcon(bm)
                .setTicker(fotomulta.getTitle())
                .setContentText(fotomulta.getMessage())
                .setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                .setWhen(System.currentTimeMillis())
                .setContentTitle(fotomulta.getTicketText())
                .setDefaults(Notification.DEFAULT_ALL);

새 활동

 private Person person;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_push);
    person = (Person) getIntent().getSerializableExtra("person");
}

행운을 빌어요!!

알림 구현에서 다음과 같은 코드를 사용합니다.

NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
...
Intent intent = new Intent(this, ExampleActivity.class);
intent.putExtra("EXTRA_KEY", "value");

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pendingIntent);
...

예제 활동에서 의도 값을 추가로 가져오려면 다음 코드를 사용합니다.

...
Intent intent = getIntent();
if(intent!=null) {
    String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...

매우 중요한 참고: Intent::putExtra() 메서드는 오버로드된 메서드입니다.추가 키를 얻으려면 Intent::get을 사용해야 합니다.[유형]추가() 메서드입니다.

참고: NOTIFICATION_IDNOTIFICATION_CHANNEL_ID는 예제 활동에서 선언된 상수입니다.

검색을 좀 한 후 안드로이드 개발자 가이드에서 솔루션을 얻었습니다.

PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

stackBuilder.addParentStack(ArticleDetailedActivity.class);

contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

테스트 활동 클래스에서 의도 값을 추가로 얻으려면 다음 코드를 작성해야 합니다.

 Intent intent = getIntent();
 String extra = intent.getStringExtra("extra") ;

보류 중으로 사용하십시오.해결되는 것보다 알림을 표시하는 동안 의도된 것입니다.

보류 중인 의도 = 보류 중Intent.get Activity(이것, 0, 알림)의도, 보류 중의도.FLAG_UPDATE_CURENT);

추가 보류 중의도.FLAG_UPDATE_CURRENT를 마지막 필드로 지정합니다.

안녕하세요, 저도 이 게시물에 언급된 모든 것과 다른 곳에서 온 몇 가지를 더 시도했다고 말할 수 있습니다.저에게 가장 큰 문제는 새로운 Intent가 항상 null 번들을 가지고 있다는 것입니다.제 문제는 "이것을 포함시켰나요, 저것을 포함시켰나요"의 세부 사항에 너무 집중하는 것이었습니다.저의 해결책은 세부 사항에서 한 발 물러서서 알림의 전반적인 구조를 살펴보는 것이었습니다.그 때 코드의 핵심 부분을 올바른 순서로 배치할 수 있었습니다.유사한 문제가 있는 경우 다음 사항을 확인하십시오.

1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);

2a. Bundle bundle = new Bundle();

//데이터 유형을 지정하는 것이 훨씬 좋습니다.예를 들어 묶음.인트

2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5.          NotificationCompat.Builder nBuilder =
                    new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_notify)
                            .setContentTitle(title)
                            .setContentText(content)
                            .setContentIntent(contentIntent)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                            .setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
                            .setColor(getResources().getColor(R.color.colorPrimary))
                            .setCategory(Notification.CATEGORY_REMINDER)
                            .setPriority(Notification.PRIORITY_HIGH)
                            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());

시퀀스를 통해 유효한 번들을 얻습니다.

사용하는 경우

android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"

활동을 시작하려면 AndroidManifest.xml 파일에서 다음을 사용해야 합니다.

Intent notificationClick = new Intent(context, NotifyActivity.class);
    Bundle bdl = new Bundle();
    bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
    notificationClick.putExtras(bdl);
    notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
    notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);  // schließt tasks der app und startet einen seperaten neuen

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotifyActivity.class);
    stackBuilder.addNextIntent(notificationClick);

    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(notificationPendingIntent);

중요한 것은 다음과 같은 고유 ID를 사용하여 고유 데이터를 설정하는 것입니다.

notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));

언급URL : https://stackoverflow.com/questions/1198558/how-to-send-parameters-from-a-notification-click-to-an-activity

반응형