我正在尝试处理应用程序中的异常。我试图记录异常,然后使用Toast来提示用户出现问题。在所有扩展Activity类的类中,我已经成功实现了这一点。
但是,在任何不扩展activity的类中,我无法使用toast方法,因为我无法获取当前上下文。是否有简单的方法可以解决这个问题,或者应该将所有类都扩展为Activity?
我正在尝试处理应用程序中的异常。我试图记录异常,然后使用Toast来提示用户出现问题。在所有扩展Activity类的类中,我已经成功实现了这一点。
但是,在任何不扩展activity的类中,我无法使用toast方法,因为我无法获取当前上下文。是否有简单的方法可以解决这个问题,或者应该将所有类都扩展为Activity?
当您从Activity类调用非活动(Non-Activity)
类时,只需传递Context即可。
YourNonActivtyClass obj = new YourNonActivtyClass(Activity.this);
setContext(context: Context)
进行设置。object AndroidContextObservable { // needs to be singleton.
private lateinit var context: Context
fun context(): Observable<Context> {
return Observable.create { subscriber ->
subscriber.onNext(this.context)
subscriber.onComplete()
}
}
fun setContext(context: Context) {
this.context = context
}
}
假设我有一个使用Google日历的服务:我首先会在我的活动中设置它:
class ViewMeetingRoomDataActivity : AppCompatActivity() {
@Inject lateinit var googleCalendarsService: GoogleCalendarService // abstraction over the GoogleCalendarAPI Class (Below)
private var subscriptions: Disposable = Disposable.empty()
private lateinit var meetingRoomBundleData: ParcelableMeetingRoomData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidContextObservable.setContext(this) // set the context here
DaggerServiceModuleComponent.create().inject(this)
setContentView(R.layout.activity_view_meeting_room_data)
}
override fun onPause() {
super.onPause()
this.subscriptions.dispose()
}
}
然后因为可观察对象来自单例,我们可以在init生命周期钩子中订阅它。
@Module
class GoogleCalendarsApiServiceModule @Inject constructor(): IGoogleCalendarsApiServiceModule {
private lateinit var googleCredential: Credential
private lateinit var googleCalendarService: Calendar
private val httpTransport: NetHttpTransport = NetHttpTransport()
private val subscriptions: Disposable = Disposable.empty()
init {
// Subscribe to the context
this.subscriptions.apply {
AndroidContextObservable.context()
.subscribe { context ->
googleCredential = GoogleCredentialsBuilder.getCredentials(httpTransport, context)
googleCalendarService = ServiceBuilder.buildGoogleCalendarService(googleCredential, httpTransport)
}
}
}
fun finalize() {
this.subscriptions.dispose() // <-- Don't forget to discard Observables :)
}
}
我喜欢这个解决方案,因为它是可测试的,并且现在的上下文来自于单一的真相来源。这是我能想到的最干净的方法,在Activity之外获取上下文。
希望我有所帮助。
Toast消息应该在应用程序上下文中工作,即:
Toast.makeText(getApplicationContext(), ...);