Programing

Android의 서비스에서 알림 보내기

lottogame 2020. 8. 20. 19:23
반응형

Android의 서비스에서 알림 보내기


서비스를 실행 중이며 알림을 보내고 싶습니다. 너무 나쁜 알림 객체는 필요 Context등을 Activity, 아니라 Service.

그것을 통과하는 방법을 알고 있습니까? Activity각 알림에 대해 를 만들려고했지만 보기 흉한 것 같고 .NET Activity없이 를 시작하는 방법을 찾을 수 없습니다 View.


모두 ActivityService실제로 extend Context그래서 당신은 간단하게 사용할 수있는 this사용자로 Context당신의 내 Service.

NotificationManager notificationManager =
    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);

이 유형의 알림은 문서에서 볼 수 있듯이 더 이상 사용되지 않습니다.

@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }

public Notification(android.os.Parcel parcel) { /* compiled code */ }

@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }

더 나은 방법
다음과 같은 알림을 보낼 수 있습니다.

// prepare intent which is triggered if the
// notification is selected

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n  = new Notification.Builder(this)
        .setContentTitle("New mail from " + "test@gmail.com")
        .setContentText("Subject")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .setAutoCancel(true)
        .addAction(R.drawable.icon, "Call", pIntent)
        .addAction(R.drawable.icon, "More", pIntent)
        .addAction(R.drawable.icon, "And more", pIntent).build();


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n); 

가장 좋은 방법은
필요 최소 API 레벨 11 이상 코드 (안드로이드 3.0).
최소 API 레벨이 11보다 낮 으면 이와 같이 지원 라이브러리 의 NotificationCompat 클래스 를 사용해야 합니다.

따라서 최소 대상 API 레벨이 4+ (Android 1.6+) 인 경우 다음을 사용하십시오.

    import android.support.v4.app.NotificationCompat;
    -------------
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.mylogo)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification()
{
    NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(R.drawable.cal_icon);
    builder.setContentText("Contents");
    builder.setContentTitle("title");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int)System.currentTimeMillis(),notification);
}

글쎄, 내 솔루션이 모범 사례인지 확실하지 않습니다. NotificationBuilder내 코드를 사용하면 다음과 같습니다.

private void showNotification() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

명백한:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleInstance"
    </activity>

그리고 여기에 서비스 :

    <service
        android:name=".services.ProtectionService"
        android:launchMode="singleTask">
    </service>

실제로 singleTaskat Service이 있는지 모르겠지만 내 응용 프로그램에서 제대로 작동합니다 ...


이 중 어느 것도 작동하지 않으면 또는 getBaseContext()대신을 시도하십시오 .contextthis

참고 URL : https://stackoverflow.com/questions/1207269/sending-a-notification-from-a-service-in-android

반응형