Приложение первого использования генерирует NPE на устройствах только с android 6 и 9. Это происходит при создании активности, широковещательных приемниках и сервисах. Пример кода:
//application
public class MyApp extends MultiDexApplication {
private static MyApp sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
...
}
public static MyApp getInstance() {
return sInstance;
}
}
//receiver
class LocalNotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
MyApp.getInstance().getAppComponent(context).inject(this)
...
}
}
//service
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
public MyFirebaseMessagingServices() {
MyApp.getInstance().getAppComponent().inject(this);
}
}
//activity
public class LaunchActivity extends AppCompatActivity implements LaunchActivityView {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
PreloginInjector.Companion.getInstance().getComponent().inject(this);
/** inside the PreloginInjector
fun getComponent(): PreloginComponent {
if (component == null) {
component = MyApp.getInstance().appComponent.makePreloginComponent(PreloginModule())
}
return component!!
}
*/
}
}
Я долго пытался повторить этот случай на эмуляторах с android 6 и 9. Я попытался запустить приложение с рабочего стола, из уведомлений, попытался восстановить приложение. Но потерпеть неудачу. Я не понимаю, почему это происходит только в 6,9 android версиях. Похоже, приложение запускается позже других. Пример трассировки стека консоли:
java.lang.RuntimeException:
1. at android.app.ActivityThread.handleCreateService (ActivityThread.java:2862)
2. at android.app.ActivityThread.access$1900 (ActivityThread.java:150)
3. at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1427)
4. at android.os.Handler.dispatchMessage (Handler.java:102)
5. at android.os.Looper.loop (Looper.java:148)
6. at android.app.ActivityThread.main (ActivityThread.java:5417)
7. at java.lang.reflect.Method.invoke (Native Method)
8. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:728)
9. at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:616)
Caused by: java.lang.NullPointerException:
1. at com.my.myapp.notifications.data.services.MyFirebaseMessagingServices.<init> (MyFirebaseMessagingServices.java:77)
2. at java.lang.Class.newInstance (Native Method)
3. at android.app.ActivityThread.handleCreateService (ActivityThread.java:2859)