문제

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

알림을 만드는 서비스가 있습니다. 사용자가 알림을 클릭하면 특수 매개 변수로 메인 활동을 열고 싶습니다. 예를 들어 항목 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") );
    }

엑스트라는 항상 무효이며 내 기록에 아무것도 얻지 못합니다.

btw ... onCreate 내 활동이 시작될 때만 실행됩니다. 활동이 이미 시작된 경우에도 엑스트라를 모아서받은 항목에 따라 내 활동을 제시하고 싶습니다.

어떤 아이디어?

도움이 되었습니까?

해결책

이 안내서를 살펴보십시오 (알림 생성) 및 샘플 apidemos "statusBarnotifications"및 "notificationDisplay".

활동이 이미 실행 중인지 관리하려면 두 가지 방법이 있습니다.

  1. 추가하다 flag_activity_single_top 활동을 시작할 때 의도에 플래그를 지정 한 다음 활동 클래스 구현에서 신생자 (의도 의도) 이벤트 핸들러, 이렇게하면 활동을 요구하는 새로운 의도에 액세스 할 수 있습니다 (getintent ()를 호출하는 것과 동일하지는 않습니다. 이것은 항상 활동을 시작한 첫 번째 의도를 반환합니다.

  2. 1 위와 동일하지만 의도에 플래그를 추가하는 대신 추가해야합니다. "Singletop" 귀하의 활동에서 AndroidManifest.xml.

의도 엑스트라를 사용하는 경우 전화를 받으십시오 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);

일부 이메일 목록 및 기타 포럼을 읽은 후이 트릭이 SOM 고유 한 데이터를 의도에 추가하는 것으로 보입니다.

이와 같이:

   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()))); 

나는 이것이 왜 해야하는지 이해하지 못한다. 그것은 의도와 관련이있는 것이 엑스트라에 의해서만 식별 될 수 없다 ...

나는 모든 것을 시도했지만 아무것도 효과가 없었습니다.

결국 다음 솔루션을 생각해 냈습니다.

1- Manifest Add for the Activity Android : LaunchMode = "Singletop"

2- 보류 의도를 유지하는 동안 다음을 수행하는 동안 의식을 직접 사용하는 대신 번들을 사용하십시오.

                    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); 

AndroidManifest.xml

launkmode 포함 = "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);

MessagedEtailSactivity.java

OnResume () - 매번 전화를 받고 엑스트라를로드하십시오.

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

그것이 도움이되기를 바랍니다. 그것은 StackoverFlow의 다른 답변을 기반으로했지만 이것은 저에게 가장 업데이트 된 것입니다.

쉽습니다. 이것은 객체를 사용하는 내 솔루션입니다!

내 포조

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");
}

행운을 빕니다!!

검색을 수행 한 후 Android Developer Guide에서 솔루션을 얻었습니다.

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") ;

사용하는 경우

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);

중요한 것은 고유 한 데이터를 설정하는 것입니다.

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

서비스 사용 PendingIntent.FLAG_UPDATE_CURRENT

나를 위해 일합니다.

해결 될 것보다 알림을 표시하는 동안 보드 인트로 사용하십시오.

보드 인텐트 의도 = pendingIntent.getActivity (this, 0, notificationIntent, pendingIntent.flag_update_current);

마지막 필드로 pendingintent.flag_update_current를 추가하십시오.

알림 구현에서 다음과 같은 코드를 사용하십시오.

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");
}
...

매우 중요한 메모 : 그만큼 의도 :: putextra () 메소드는 과부하 된 것입니다. 추가 키를 얻으려면 사용해야합니다. 의도 :: get [type] extra () 방법.

메모: notification_id 그리고 notification_channel_id 예를 보여준 상수입니다

G'day, 나도이 게시물에 언급 된 모든 것을 시도했으며 다른 곳에서 몇 가지를 더 시도했다고 말할 수 있습니다. 나에게 #1 문제는 새로운 의도에 항상 널 번들이 있다는 것입니다. 내 문제는 "내가 포함했거나. 내 솔루션은 세부 사항에서 한 걸음 물러나고 알림의 전반적인 구조를 살펴 보는 것이 었습니다. 그렇게했을 때 코드의 주요 부분을 올바른 순서로 배치했습니다. 따라서 비슷한 문제가있는 경우 다음을 확인하십시오.

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

2a. Bundle bundle = new Bundle();

// 데이터 유형을 훨씬 더 잘 지정하는 것이 좋습니다. EG Bundle.PUTINT

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());

이것으로 순서 유효한 번들이 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top