2017-02-05 2 views
1

Android 애플리케이션에서 NotificationHelper를 만들었습니다. 이는 앱 전체에서 내 알림을 처리하기위한 것입니다. 난의 말 있도록 조각을 내 두 가지 방법 (showNotification + stopNotification)를 이동하는 경우 도우미 클래스에서 PendingIntent를 호출하십시오.

그리고

은, 다음의 완벽하게 잘 :-)

그러나 순간 작동, 나는 같은 두 가지 방법 (방법은 액세스하려고 ('

을 그리고 그 이유를 나는 거의 3 시간 동안 지금 알아 내기 위해 노력 해왔다 ??

exception from log.cat

IT는 다음과 같습니다 내 NotificationHandler에서) 동일, 그럼 내가이 예외를 얻을! 이자형 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을 호출합니까? 도우미 클래스는 일반적으로 정적 메서드로 완료되며 Application을 확장하지 않고 컨텍스트를 전달해야합니다. – 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 변수마다 시간을 사용합니다. Activitythis의 메소드를 Context으로, FragmentgetActivity()Context으로 사용할 수 있습니다.

+0

WOW 감사합니다. David! 나는 지금 그 방법에 대한 문맥을 잊어 버리는 것을 본다. 반죽! –

+0

나는 생각 반죽이있다?! 부분적으로 이유가 있습니까, 왜 helperclass가 항상 정적이어야합니까 ?? –

+0

'정적'은 ** 필수 항목이 아닙니다 ** 일반적으로 어디서나 호출 할 수있는 도우미 클래스에 메서드를 수집하므로 클래스에 멤버 변수 등의 상태가 필요하지 않으므로 방법은'고정'일 수있다. 단지 최선의 방법 일뿐입니다. –

관련 문제