在我的项目中,我需要在获取请求并开始导航到另一个片段之前检查我的初始屏幕上的互联网连接,我还有视图模型集成,并且我的应用程序在显示没有互联网布局之前崩溃了。(如果获取请求没有问题互联网正在运行)。每个检查 Internet 连接的指南都不能帮助我解决问题。
@AndroidEntryPoint
class SplashFragment : Fragment() {
lateinit var binding: FragmentSplashBinding
private val viewmodel by viewModels<SplashViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSplashBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewmodel.initResponse()
viewmodel.state.observe(viewLifecycleOwner){
resp->
if(resp.isSuccessful){
binding.internetLayout.visibility = VISIBLE
Navigation.findNavController(view).navigate(R.id.action_splashFragment_to_authFragment)
} else{
isDeviceOnline(requireContext())
resp.errorBody()?.string()
binding.internetLayout.visibility = INVISIBLE
binding.noInternetLayout.visibility = VISIBLE
}
}
}
private fun isDeviceOnline(context: Context): Boolean {
val connManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connManager.getNetworkCapabilities(connManager.activeNetwork)
if (networkCapabilities == null) {
Log.d("TAG", "Device Offline")
return false
} else {
Log.d("TAG", "Device Online")
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)
) {
Log.d("TAG", "Connected to Internet")
return true
} else {
Log.d("TAG", "Not connected to Internet")
return false
}
}
} else {
val activeNetwork = connManager.activeNetworkInfo
if (activeNetwork?.isConnectedOrConnecting == true && activeNetwork.isAvailable) {
Log.d("TAG", "Device Online")
when (activeNetwork.state) {
NetworkInfo.State.CONNECTED -> {
Log.d("TAG", " CONNECTED ")
return true
}
NetworkInfo.State.CONNECTING -> {
Log.d("TAG", " CONNECTING ")
return true
}
else -> {
Log.d("TAG", "NO Connection")
return false
}
}
} else {
Log.d("TAG", "Device Offline")
return false
}
}
}
}
@HiltViewModel
class SplashViewModel@Inject constructor(private val repository: RouteRepository,
private val app:Application
)
:ViewModel() {
val _state = MutableLiveData<Response<RouteModel>>()
val state : LiveData<Response<RouteModel>> = _state
init {
initResponse()
}
@SuppressLint("SuspiciousIndentation")
fun initResponse(){
viewModelScope.launch {
_state.value = repository.getRoute()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@drawable/appinit"
>
<RelativeLayout
android:id="@+id/internetLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="57dp"
android:layout_height="54dp"
android:layout_centerInParent="true"
android:layout_marginBottom="256dp"
android:src="@drawable/splashlogo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/noInternetLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:visibility="invisible"
android:id="@+id/no_internet_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:fontFamily="@font/boldtextstyle"
android:text="Opps,something went wrong with Internet:(("
android:textAllCaps="true"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<TextView
android:visibility="invisible"
android:id="@+id/no_internet_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/no_internet_heading"
android:layout_centerHorizontal="true"
android:layout_marginHorizontal="64dp"
android:layout_marginVertical="32dp"
android:fontFamily="@font/boldtextstyle"
android:gravity="center"
android:text="Check your Internet Connection and Try Again"
android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
</RelativeLayout>
</RelativeLayout>