Using Application context everywhere?

后端 未结 9 1003
难免孤独
难免孤独 2020-11-22 01:52

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instan         


        
9条回答
  •  没有蜡笔的小新
    2020-11-22 01:55

    I would use Application Context to get a System Service in the constructor. This eases testing & benefits from composition

    public class MyActivity extends Activity {
    
        private final NotificationManager notificationManager;
    
        public MyActivity() {
           this(MyApp.getContext().getSystemService(NOTIFICATION_SERVICE));
        }
    
        public MyActivity(NotificationManager notificationManager) {
           this.notificationManager = notificationManager;
        }
    
        // onCreate etc
    
    }
    

    Test class would then use the overloaded constructor.

    Android would use the default constructor.

提交回复
热议问题