2017-02-05 16 views
1

Я сделал NotificationHelper в своем приложении для Android, которое предназначено для обработки моих уведомлений по всему приложению.Call PendingIntent из класса-помощника

И если я пошевелить два метода (showNotification + stopNotification), чтобы, скажем, фрагмент, то его прекрасно работает прекрасный :-)

Но в тот момент, я пытаюсь достигнуть тех же двух методов (методы являются идентичны) от моего NotificationHandler, то я получаю это исключение: '(

И я пытался выяснить, в настоящее время почти 3 часа, почему это ??

exception from log.cat

похоже! е rror относится к: getApplicationContext() в этой строке:

PendingIntent pendingIntent = PendingIntent.getActivity (getApplicationContext(), 0, myIntent, Intent.FILL_IN_ACTION);

=== Вот мой NotificationHandler ===

public class NoteHandler extends Application { 



/** 
* Empty constructor 
*/ 
public NoteHandler() { 

} 

/** 
* Turning Notification ON 
*/ 
public void showNotification() { 



    Intent myIntent = new Intent(this, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, myIntent, Intent.FILL_IN_ACTION); 

    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(getApplicationContext()) 
        // Setting LIGHTS and RINGTONE 
        .setLights(Color.WHITE, 300, 100) 
        //.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) 
        // Setting the ICONS 
        //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.btn_switch_flash_on)) 
        .setSmallIcon(R.mipmap.ic_launcher) 
        // Setting the CONTENT 
        .setContentTitle(getString(R.string.app_name)) 
        .setContentText(getString(R.string.app_notification_flash)) 
        // Setting the INTENT 
        .setContentIntent(pendingIntent) 
        .setOngoing(true); 

    // Setting the color of SmallIconBackground (only for Android API 21 and above...) 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     mBuilder.setColor(Color.parseColor("#6b394c")); 
    } 

    // Setting Priority to MAX (only for Android API 16 and above...) 
    if (android.os.Build.VERSION.SDK_INT >= 16) { 
     mBuilder.setPriority(Notification.PRIORITY_MAX); 
    } 

    // Sets an ID for the notification 
    int mNotificationId = 1; 
    // Gets an instance of the NotificationManager service 
    NotificationManager mNotifyMgr = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE); 
    // Builds the notification and issues it. 
    mNotifyMgr.notify(mNotificationId, mBuilder.build()); 
} 

/** 
* Turning Notification OFF 
*/ 
public void stopNotification() { 
    int mNotificationId = 1; 
    NotificationManager mNotifyMgr = 
      (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE); 
    mNotifyMgr.cancel(mNotificationId); 
} 

}

+1

От кого вызывается showNotification? Класс помощника обычно выполняется со статическим методом, и вам нужно передать контекст в него, а не путем расширения приложения. – shtolik

+0

Поскольку этот помощник склонен заботиться о уведомлении, тогда я использую статические методы ... Я звоню из MainActivity и Fragments –

ответ

0

Создать вспомогательный класс, содержащий только статические методы. Удалите это из класса Application. Поскольку для статических методов требуется доступ к Context, просто передайте это как параметр, когда вы его вызываете. Пример:

public static void showNotification(Context context) { 
    Intent myIntent = new Intent(context, MainActivity.class); 
    PendingIntent pendingIntent = 
     PendingIntent.getActivity(context, 0, myIntent, Intent.FILL_IN_ACTION); 
    ... 
} 

Использование командной context переменной каждый раз, когда вам нужно Context. Ваш Activity должен вызвать метод с this как Context, а ваш Fragment может использовать getActivity() как Context.

+0

WOW Спасибо, Дэвид! Теперь я вижу, что забыл передать в контексте метод ... Тесто! –

+0

У меня есть мысль?! Есть ли какая-то враждебная причина, почему helperclass всегда должен быть статичным? –

+0

«static» не является ** обязательным **, но обычно вы собираете методы в вспомогательные классы, которые могут быть вызваны из любого места, поэтому классу не нужно иметь какое-либо состояние (то есть: переменные-члены), поэтому методы могут быть «статическими». Это просто лучшая практика. –