2016-04-14 3 views
-1

ich unten Code konfigurieren müssen generieren Benachrichtigung:getActivity als null in Fragmente erhalten, wenn vom Notification Hause Aktivität lunching

Intent intent = new Intent(this, HomeActivity.class); 
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); 


     intent.putExtra("IsNotification",true); 

     int mNotificationId= Pref.getValue(this, Constants.NOTIFICATION_ID,1); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this,mNotificationId /* Request code */, intent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 

     Bitmap mBitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(mBitmap) 
       .setContentTitle("App Notification").setColor(getResources().getColor(R.color.orange)) 
       .setContentText(message) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(mNotificationId /* ID of notification */, notificationBuilder.build()); 

     mNotificationId++; 

     Pref.setValue(this,Constants.NOTIFICATION_ID,mNotificationId); 

Jetzt in Manifest habe ich

<activity 
      android:name=".HomeActivity" 
      android:label="@string/title_activity_home" 
      android:screenOrientation="portrait" 
      android:windowSoftInputMode="adjustPan" 
      android:launchMode="singleTop" 
      /> 

Jetzt in OnCreate und onNewIntent auf beiden Ich überprüfe, dass es Bündel hat einige Benachrichtigung Wert

Wie unten Code commit Fragment von OnCreate oder onNewIntent hängen von Aktivität Instanz:

private void initNotification(){ 

     if(mNotitficationFragment==null){ 

      mNotitficationFragment= NotitficationFragment.newInstance(); 
     } 

     if(!mNotitficationFragment.isAdded()){ 

      mFragManager.beginTransaction().replace(R.id.frame_home_container,mNotitficationFragment).commit(); 

     } 



    } 

meine Ausgabe So jetzt ist, wenn onCreateView von NotificationFragment es heißt `getActivity() als null geben.

HINWEIS

Für Fragment ich bin mit support-v4:23.1.1 für Fragment.

+0

Was ist, wenn Sie einen Kontext in 'Frgament onAttach (...)' haben? Als [dies] (http://stackoverflow.com/questions/6215239/getactivity-returns-null-in-fragment-function) post sagte –

+0

@MD ich muss überprüfen, dass – Herry

+0

@MD auch als veraltet für onAttach angezeigt wird (Activity mactivity) – Herry

Antwort

0

Versuchen Sie die entsprechende Verarbeitung an oder nach onActivityCreated oder in onAttach. Überprüfen Sie für die onAttach veraltete Warnung dieses answer.

Verwandte Themen