2015-08-13 125 views
0

當我的應用程序關閉時(即用戶從應用程序切換菜單中刷掉),它崩潰在onMessageReceived()應用程序在收到的gcm消息關閉時崩潰

這裏的onMessageReceived()

@Override 
public void onMessageReceived(String from, Bundle data) { 
    String message = data.getString("message"); 
    from = data.getString("sender"); 

    File notificationsFile = Constants.getNotificationsFlagFile(); 
    ... 
} 

它崩潰的最後一行,給人一種null pointer exception

08-13 21:15:25.535 23201-23216/com.example.myapp E/AndroidRuntime: 致命異常:AsyncTask#1 java.lang.ExceptionInInitializerError at com.example.myapp.chatGCM.MyGcmListenerService.onMessageReceived(MyGcmListenerService.java:52) at com.google.android.gms.gcm.GcmListenerSe rvice.zzs(Unknown Source) at com.google.android.gms.gcm.GcmListenerService.zzk(Unknown Source) at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source) at com.google .android.gms.gcm.GcmListenerService $ 1.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java :573) at java.lang.Thread.run(Thread.java:841)引起:java.lang.NullPointerException at helpers.Constants。(Constants.java:54) at com.example.myapp.chatGCM。 MyGcmListenerService.onMessageReceived(MyGcmListenerService.java:52) at com.google.android.gms.g cm.GcmListenerService.zzs(Unknown Source) at com.google.android.gms.gcm.GcmListenerService.zzk(Unknown Source) at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source) at com .google.android.gms.gcm.GcmListenerService $ 1.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor的.java:573) 在java.lang.Thread.run(Thread.java:841)

和這裏的getNotificationsFlagFile()

public static File getNotificationsFlagFile() 
{ 
    return new File(MainApplication.getAppContext().getFilesDir(), "notifications_"+getSession()); 
} 

最後:

private static String getSession() 
{ 
    File file = new File(MainApplication.getAppContext().getFilesDir(), "session"); 
    int length = (int) file.length(); 
    byte[] bytes = new byte[length]; 
    FileInputStream in = null; 
    try { 
     in = new FileInputStream(file); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    try { 
     try { 
      in.read(bytes); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } finally { 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return (new String(bytes)); 
} 

所有我使用的是靜態的變量和函數。這是爲什麼發生?

回答

0

From here您似乎有一個不可預料的行爲...可能從getAppContext()功能...嘗試使用getApplicationContext()來代替。

+0

你有些不對。 'getAppContext()'是'MainApplication'中的靜態方法,它返回'MainApplication.context;',它在'MainApplication'的'onCreate()'中被初始化。應用程序關閉後,尚未「創建」。 –

相關問題