こんにちは、私はIntentService
を使用して、notificationCalendar
変数に格納されている時間の設定に基づいて通知を表示しています。私はAlarmManager
を使用してサービスを開始し、アプリがバックグラウンド(ホームボタンを押した状態)または実行中の場合は通知を受け取りますが、最近のアプリからアプリをスワイプすると通知は受信されません。最近のアプリからスワイプしたアプリケーションの後にサービスコードが実行されない
サービスを無効にできないために解決策を探しましたので、START_STICKY
をサービスonStartCaommand
に返し、マニフェストにはstopWithTask=false
を追加しました。
public class NotificationService extends Service {
private static final int NOTIFICATION_ID = 1;
public NotificationService() {
super();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
processStartNotification();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Habit Time")
.setContentText("Hey time for your habit")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(alarmSound)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
}
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
//マニフェストファイル
:通知を表示するprivate void sendNotification(){
Intent intent = new Intent(this, NotificationService.class);
PendingIntent alarmIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
サービスクラス:私はAPIレベルここ22
とMIの電話でそれをテストしてい
は私のコードです
<service
android:name=".notification.NotificationService"
android:enabled="true"
android:stopWithTask="false"/>
を管理します!スティッキーサービスを望むなら、 'IntentService'ではなく' Service'を拡張する必要があります。 –
@DavidWasserサービスに変更しましたがまだ動作していません –
あなたの改訂コードを投稿してください(あなたの現在の実装でポストを更新してください)。 –