1

В чем может быть проблема? Хочу реализовать общий класс для уведомлений, вот ->

   package com.example.artem_molodcov.twoontwo;

   import android.app.Notification;
   import android.app.NotificationManager;
   import android.app.PendingIntent;
   import android.content.Context;
   import android.content.Intent;
   import android.content.res.Resources;
   import android.os.Bundle;
   import android.support.v7.app.AppCompatActivity;

   public class NotificationClass extends AppCompatActivity {

        //id notify
        private static final int NOTIFY_ID = 101;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }

        public void notificationCreate(String act) {

             String notify_title = "Уведомление",
                    notify_text  = "";

             switch (act) {
                   case "authTrue":
                      notify_text = "Авторизация прошла успешно.";
                   break;
                   default:
                      notify_text = "Что-то то приключилось у вас.";
                   break;
             }

             Context context = getApplicationContext();

             Intent notificationIntent = new Intent(context, MainActivity.class);
              PendingIntent contentIntent = PendingIntent.getActivity(context,
              0, notificationIntent,
             PendingIntent.FLAG_CANCEL_CURRENT);

             Resources res = context.getResources();
             Notification.Builder builder = new Notification.Builder(context);

              builder.setContentIntent(contentIntent)
                 .setSmallIcon(R.drawable.ic_notifications_white_18dp)
                 .setWhen(System.currentTimeMillis())
                 .setAutoCancel(true)
                 .setContentTitle(notify_title)
                 .setContentText(notify_text);

              Notification notification = builder.build();

              NotificationManager notificationManager = (NotificationManager) context
             .getSystemService(Context.NOTIFICATION_SERVICE);
             notificationManager.notify(NOTIFY_ID, notification);
    }
 }

Если код прописанный в notificationCrate вставить не классом, а как обычно, то все работает, а если так:

    NotificationClass notificationClass = new NotificationClass();
    notificationClass.notificationCreate("authTrue");

То приложение вылетает. Подскажите, что не так.

1 ответ 1

4

У вас выпадает NullPointerException т.к. метод getApplicationContext() возвращает null т.к. создавая активити таким образом вы не привязываете её к системе и она не имеет доступа к контексту.

Решение:

  1. Ваш класс-утилита не должен наследовать активити.
  2. Контекст надо передать в метод в качестве аргумента и использовать ссылку на него.

public class NotificationClass {

    //id notify
    private static final int NOTIFY_ID = 101;

    public void notificationCreate(Context ctx, String act) {

         //теперь ctx не null
         ...
    }
}

Вызывать в классе активити так:

NotificationClass notificationClass = new NotificationClass();
notificationClass.notificationCreate(this, "authTrue");

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.