Уведомление не отображается, если это необходимо через некоторое время. но работает только на месте

У меня в приложении 3 кнопки

Первая кнопка показывает уведомление о нажатии кнопки.

Вторая кнопка отменяет показанное уведомление.

Третья кнопка должна показывать уведомление через 5 секунд.

Первая и вторая кнопки работают, но третья не работает. это не показывает какую-либо ошибку в компиляции. Кто-нибудь может сказать мне, что не так с этим куском кода?

public void setAlarm(View view) {
        Long alertTime=new GregorianCalendar().getTimeInMillis()+5000;
        Intent alertIntent=new Intent(this,AlertReceiver.class);
        AlarmManager alarmManager=(AlarmManager)
                getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
                 PendingIntent.getBroadcast(this,1, alertIntent,
                         PendingIntent.FLAG_UPDATE_CURRENT));
    }

Вот моя полная деятельность Основной класс

package com.test.notification2;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.GregorianCalendar;

public class MainActivity extends AppCompatActivity {

    Button showNotificationBut, stopNotificationBut,alertButton;
    NotificationManager notificationManager;

    boolean isNotificActive=false;

    int notifID=33;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        showNotificationBut=(Button)findViewById(R.id.showNotificationBut);
        stopNotificationBut=(Button)findViewById(R.id.stopNotificationBut);
        alertButton=(Button)findViewById(R.id.alertButton);


    }


    public void showNotification(View view) {
        NotificationCompat.Builder notificBuilder= new
                NotificationCompat.Builder(this)
                .setContentTitle("Message")
                .setContentText("New Message")
                .setTicker("Alert New Message")
                .setSmallIcon(R.drawable.my_image);

        Intent moreInfoIntent=new Intent(this,MoreInfoNotification.class);

        TaskStackBuilder taskStackBuilder=TaskStackBuilder.create(this);
        taskStackBuilder.addParentStack(MoreInfoNotification.class);
        taskStackBuilder.addNextIntent(moreInfoIntent);
        PendingIntent pendingIntent=taskStackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notificBuilder.setContentIntent(pendingIntent);

        notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notifID, notificBuilder.build());
        isNotificActive=true;


    }

    public void stopNotification(View view) {
        if(isNotificActive){
            notificationManager.cancel(notifID);
        }
    }

    public void setAlarm(View view) {
        Long alertTime=new GregorianCalendar().getTimeInMillis()+5000;
        String s = String.valueOf(alertTime);
        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();

        Intent alertIntent=new Intent(this,AlertReceiver.class);
        AlarmManager alarmManager=(AlarmManager)
                getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
                 PendingIntent.getBroadcast(this,1, alertIntent,
                         PendingIntent.FLAG_UPDATE_CURRENT));
    }
}

Вот класс AlertReceiver:

package com.test.notification2;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

/**
 * Created by waqas on 13/05/2016.
 */
public class AlertReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
       createNotification(context,"Times up","5 seconds has passed",
               "Alert");
    }
    public void createNotification(Context context,String msg,String msgText, String  msgAlert){
        PendingIntent notificIntent=PendingIntent.getActivity(context, 0,
                new Intent(context,MainActivity.class),0);
        NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.my_image)
                .setContentTitle(msg)
                .setTicker(msgAlert)
                .setContentText(msgText);
        mBuilder.setContentIntent(notificIntent);
        mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager=
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1,mBuilder.build());

    }
}

1 ответ

Решение

Этот код работает нормально. Вы зарегистрировали услугу в манифесте?

        <receiver android:name=".AlertReceiver">
    </receiver>
Другие вопросы по тегам