티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to send parameters from a notification-click to an activity?
알림 클릭 시에 액티비티로 어떻게 매개변수를 전달하나요?
문제 내용
I can find a way to send parameters to my activity from my notification.
알림에서 액티비티로 매개변수를 보내는 방법을 찾을 수 있습니다.
I have a service that creates a notification. When the user clicks on the notification I want to open my main activity with some special parameters. E.g an item id, so my activity can load and present a special item detail view. More specific, I'm downloading a file, and when the file is downloaded I want the notification to have an intent that when clicked it opens my activity in a special mode. I have tried to use putExtra
on my intent, but cant seem to extract it, so I think I'm doing it wrong.
저는 서비스를 가지고 있고, 이 서비스는 알림을 만듭니다. 사용자가 알림을 클릭하면 특별한 매개변수와 함께 내 주요 액티비티를 열고 싶습니다. 예를 들어, 항목 ID 같은 것으로, 이렇게 하면 내 액티비티가 특별한 항목 세부 정보보기를로드하고 제공할 수 있습니다. 더 구체적으로 말하면, 파일을 다운로드하고 파일이 다운로드되면 알림이 클릭될 때 특별한 모드에서 내 액티비티가 열리도록 하는 의도가 있습니다. 저는 putExtra를 사용해보았지만 추출할 수 없는 것 같아 잘못 사용하고 있는 것 같습니다.
Code from my service that creates the Notification:
제 서비스에서 알림을 생성하는 코드입니다.
// 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);
Code from my Activity that tries to fetch the extra parameter from the notification:
알림에서 extra 파라미터를 가져오려고 시도하는 내 액티비티의 코드입니다.
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") );
}
The extras is always null and I never gets anything into my log.
extras는 항상 null이며 로그에 아무것도 기록되지 않습니다.
Btw... the onCreate
is only run when my activity starts, if my activity is already started I also want to collect the extras and present my activity according to the item_id I receive.
그리고.. onCreate()는 내 액티비티가 시작될 때만 실행되고, 내 액티비티가 이미 시작되어 있는 경우에도 extra를 수집하여 item_id에 따라 내 액티비티를 표시하고 싶습니다.
Any ideas?
어떤 아이디어가 있나요?
높은 점수를 받은 Solution
Take a look at this guide (creating a notification) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".
이 가이드(알림 만들기)와 샘플 ApiDemos "StatusBarNotifications"과 "NotificationDisplay"를 살펴보세요.
For managing if the activity is already running you have two ways:
이미 실행 중인 액티비티를 관리하는 방법에는 두 가지가 있습니다:
- Add FLAG_ACTIVITY_SINGLE_TOP flag to the Intent when launching the activity, and then in the activity class implement onNewIntent(Intent intent) event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.
- Same as number one, but instead of adding a flag to the Intent you must add "singleTop" in your activity AndroidManifest.xml.
1. 액티비티를 시작할 때 Intent에 FLAG_ACTIVITY_SINGLE\_TOP 플래그를 추가하고, 액티비티 클래스에서 onNewIntent(Intent intent) 이벤트 핸들러를 구현합니다. 그러면 액티비티를 호출하는 새로운 인텐트에 접근할 수 있습니다(getIntent()를 호출하는 것과는 다릅니다. 이는 항상 액티비티를 처음 시작할 때 전달된 인텐트를 반환합니다).
2. 첫 번째 방법과 동일하지만, Intent에 플래그를 추가하는 대신 액티비티의 AndroidManifest.xml에 "singleTop"을 추가합니다.
If you use intent extras, remeber to call PendingIntent.getActivity()
with the flag PendingIntent.FLAG_UPDATE_CURRENT
, otherwise the same extras will be reused for every notification.
인텐트 extra를 사용하는 경우, PendingIntent.getActivity()를 PendingIntent.FLAG_UPDATE_CURRENT 플래그와 함께 호출해야합니다. 그렇지 않으면 같은 extra가 모든 알림에 재사용됩니다.
가장 최근 달린 Solution
In your notification implementation, use a code like this:
알림 구현에서 다음과 같은 코드를 사용하세요:
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);
...
To Get Intent extra values in the ExampleActivity, use the following code:
예시 액티비티에서 인텐트 extra 값을 가져오기 위해서는 다음과 같은 코드를 사용합니다.
...
Intent intent = getIntent();
if(intent!=null) {
String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...
VERY IMPORTANT NOTE: the Intent::putExtra() method is an Overloaded one. To get the extra key, you need to use Intent::get[Type]Extra() method.
매우 중요한 참고 사항: Intent::putExtra() 메소드는 오버로드 된 메소드입니다. extra key를 가져 오려면 Intent::get[Type]Extra() 메소드를 사용해야합니다.
Note: NOTIFICATION_ID and NOTIFICATION_CHANNEL_ID are an constants declared in ExampleActivity
참고: NOTIFICATION_ID 및 NOTIFICATION_CHANNEL_ID는 ExampleActivity에서 선언 된 상수입니다.
출처 : https://stackoverflow.com/questions/1198558/how-to-send-parameters-from-a-notification-click-to-an-activity
'개발 > 안드로이드' 카테고리의 다른 글
Android View의 상단과 하단에 테두리 쉽게 추가하기 (0) | 2022.12.26 |
---|---|
이전 액티비티로 돌아가면서 다른 액티비티 스택 모두 지우기 (0) | 2022.12.25 |
EditText에 포커스가 맞춰질 때 소프트 키보드 보여주기 (0) | 2022.12.25 |
ScrollView 안에 HorizontalScrollView가 있는 경우 터치 핸들링하기 (0) | 2022.12.25 |
'AppDatabase_Impl does not exist' 오류 수정하기 (0) | 2022.12.24 |