Невозможно показать уведомления - PullRequest
0 голосов
/ 15 апреля 2020

У меня есть какое-то уведомление в приложении для показа пользователям в указанное c время, но ничего не отображается. Я использую случайный порядок для установки идентификатора ожидающего намерения и идентификатора уведомления, поскольку в одну и ту же дату может быть несколько уведомлений.

Настройка будильника:

final int random = new Random().nextInt(100000);
                    myCalendar.set(Calendar.HOUR_OF_DAY, 7);
                    myCalendar.set(Calendar.MINUTE, 0);
                    Intent p = new Intent(getApplicationContext(), ReminderAlarmManager.class);
                    p.putExtra("title",mName.getText());
                    PendingIntent alarmIntent = PendingIntent.getActivity(getApplicationContext(), random, p, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    alarmManager.set(AlarmManager.RTC_WAKEUP,myCalendar.getTimeInMillis(),alarmIntent);
                    Toast.makeText(Revisit.this,"Reminder Set",Toast.LENGTH_SHORT).show();

широковещательный приемник:

public class ReminderAlarmManager extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Intent i = new Intent(context, ReminderNotificationService.class);
    i.putExtra("title",intent.getStringExtra("title"));
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        context.startForegroundService(i);
    } else {
        context.startService(i);
    }
}

}

Служба уведомлений:

public class ReminderNotificationService extends IntentService {
/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public ReminderNotificationService(String name) {
    super(name);
}

@Override
public void onCreate() {
    super.onCreate();

    final String CHANNEL_ID = "Blufish_Employees";
    final String CHANNEL_NAME = "Blufish";
    final String CHANNEL_DESC = "Blufish Employees Reminder Notifications";
    final int NOTIFICATION_ID = new Random().nextInt(100000);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        mChannel.setDescription(CHANNEL_DESC);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("Blufish")
            .setContentText("App is running in background.")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        startForeground(NOTIFICATION_ID,mBuilder.build());
    }
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {

    final String CHANNEL_ID = "Blufish_Employees";
    final String CHANNEL_NAME = "Blufish";
    final String CHANNEL_DESC = "Blufish Employees Reminder Notifications";
    final int NOTIFICATION_ID = new Random().nextInt(100000);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        mChannel.setDescription(CHANNEL_DESC);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(mChannel);
    }

    String title = intent.getStringExtra("title");

    Context context = getApplicationContext();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            context,CHANNEL_ID);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mBuilder.setContentTitle(title);
    mBuilder.setContentText("You are reminded to visit today.");
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setSound(uri);
    mBuilder.setAutoCancel(true);

    Intent notificationIntent = new Intent(this, SplashScreen.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    mBuilder.setContentIntent(contentIntent);
    NotificationManagerCompat managerCompat = NotificationManagerCompat.from(getApplicationContext());
    managerCompat.notify(NOTIFICATION_ID, mBuilder.build());
}

@Override
public void onDestroy() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        stopForeground(true);
    }
    super.onDestroy();
}

}

Часть в манифесте, касающаяся этого:

<receiver android:name=".ReminderAlarmManager">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service android:name=".ReminderNotificationService"
        android:enabled="true"/>

Но ничего не показывает независимо от того, работает приложение или нет ... Что я делаю не так? Пожалуйста, сообщите мне, можно ли улучшить код.

Ошибка:

2020-04-15 18:13:50.731 12773-12773/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.Blufish.blufish, PID: 12773
java.lang.RuntimeException: Unable to instantiate service com.Blufish.blufish.ReminderNotificationService: java.lang.InstantiationException: java.lang.Class<com.Blufish.blufish.ReminderNotificationService> has no zero argument constructor
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:4141)
    at android.app.ActivityThread.access$1500(ActivityThread.java:268)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1998)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7814)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
 Caused by: java.lang.InstantiationException: java.lang.Class<com.Blufish.blufish.ReminderNotificationService> has no zero argument constructor
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:129)
    at androidx.core.app.CoreComponentFactory.instantiateService(CoreComponentFactory.java:66)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:4136)
    at android.app.ActivityThread.access$1500(ActivityThread.java:268) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1998) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:237) 
    at android.app.ActivityThread.main(ActivityThread.java:7814) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...