这里我有一个泼水活动,在这里我希望它产生零食栏按摩,当他们没有找到互联网连接并且还有一个重试选项....当点击重试它再次检查互联网连接然后转到下一步活动....帮助我
package com.apkglobal.pocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import com.apkglobal.pocket.R;
public class SplashActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT=2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run(){
Intent i= new Intent(SplashActivity.this,NavigationActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
答案 0 :(得分:1)
这是ping服务器,然后在主线程
上返回结果的简单解决方案 private void showSnackIfOffline(){
final boolean online = isOnline();
runOnUiThread(new TimerTask() { //must run on main thread to update UI (show Snackbar), can be used only in Activity (FragmentActivity, AppCompatActivity...)
@Override
public void run() {
if(!online)
Snackbar.make(findViewById(android.R.id.content), "Sorry, you're offline", Snackbar.LENGTH_SHORT);
else{
/*
Your code here if user is online
*/
}
}
});
}
private boolean isOnline(){
try {
return Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8").waitFor() == 0; // "8.8.8.8" is the server to ping
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
答案 1 :(得分:0)
试试这个
if(!isConnectedToInternet()){
//Show snackbar..please tell me you know how to show a snackbar
}
private boolean isConnectedToInternet(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
在AndroidManifest.xml中添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 2 :(得分:0)
private boolean isConnectedToInternet(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
if(!isConnectedToInternet()){
showSnackBar("please check your internet connection",your_layout_name);
}
public void showSnackBar(String string, LinearLayout linearLayout)
{
snackbar = Snackbar
.make(linearLayout, string, Snackbar.LENGTH_INDEFINITE).
setAction("Ok", new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
});
snackbar.show();
}
快乐编码:)
答案 3 :(得分:0)
我的示例实现是Kotlin中Snackbar的网络状态通知。也许会帮助某人。我为侦听器设置了网络状态。小吃栏可以在任何屏幕上弹出!
interface INetworkAvailabilityNotification {
fun init()
}
class NetworkAvailabilityNotificationImpl(
val context: Context,
private val networkStateProvider: INetworkStateProvider,
resourcesInteractor: IResourcesInteractor) : INetworkAvailabilityNotification {
private var weekReferenceActivity: WeakReference<Activity>? = null
private var snackbar: Snackbar? = null
private val networkUnavailableText: String by lazy { resourcesInteractor.getString(R.string.network_unavailable_error) }
override fun init() {
initActivityCallback()
initOnlineListener()
}
private fun showSnackbar(message: String) {
initSnackBar()
setText(message)
snackbar?.show()
}
private fun setViewParams() {
snackbar?.let {
val layoutParams =
(it.view.layoutParams as FrameLayout.LayoutParams)
.also { lp -> lp.setMargins(0, 0, 0, 0) }
it.view.setBackgroundColor(Color.BLACK)
it.view.layoutParams = layoutParams
it.view.alpha = 0.90f
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
it.view.elevation = 0f
}
}
}
private fun initActivityCallback() = (context as? Application)?.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacksImpl() {
override fun onActivityResumed(activity: Activity?) {
activity?.let { weekReferenceActivity = WeakReference(activity) }
}
})
private fun initSnackBar() = weekReferenceActivity?.get()?.findViewById<View>(android.R.id.content)?.let { view ->
if (weekReferenceActivity?.get() is AppCompatActivity) {
snackbar = Snackbar.make(view, "", Snackbar.LENGTH_INDEFINITE).setBehavior(NoSwipeBehavior())
setViewParams()
}
}
private fun initOnlineListener() {
networkStateProvider.isOnline.observe { isOnline ->
if (isOnline) snackbar?.dismiss() else showSnackbar(networkUnavailableText)
}
}
private fun setText(message: String) {
val spannableString = SpannableString(message).apply {
setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.white)), 0, message.length, 0)
}
snackbar?.setText(spannableString)
}
}
internal class NoSwipeBehavior : BaseTransientBottomBar.Behavior() {
override fun canSwipeDismissView(child: View): Boolean = false
}
open class ActivityLifecycleCallbacksImpl : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {}
override fun onActivityResumed(activity: Activity?) {}
override fun onActivityStarted(activity: Activity?) {}
override fun onActivityDestroyed(activity: Activity?) {}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}
override fun onActivityStopped(activity: Activity?) {}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}
}
网络状态等级
interface INetworkStateProvider {
val stateLiveData: LiveData<SealedNetworkState>
val isOnline: LiveData<Boolean>
}
class NetworkStateProviderImpl(private val context: Context) : INetworkStateProvider {
private companion object {
const val CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"
const val WIFI_STATE_CHANGED = "android.net.wifi.WIFI_STATE_CHANGED"
}
private val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) = this@NetworkStateProviderImpl.onReceive()
}
override val stateLiveData: MutableLiveData<SealedNetworkState> = object : MutableLiveData<SealedNetworkState>() {
override fun onActive() = registerBroadcastReceiver()
override fun onInactive() = unregisterBroadcastReceiver()
}
override val isOnline: MutableLiveData<Boolean> = stateLiveData.map {
connectivityManager.activeNetworkInfo?.isConnected == true
}.distinctUntilChanged()
private fun registerBroadcastReceiver() {
context.registerReceiver(broadcastReceiver, IntentFilter().apply {
addAction(CONNECTIVITY_CHANGE)
addAction(WIFI_STATE_CHANGED)
})
}
private fun unregisterBroadcastReceiver() = context.unregisterReceiver(broadcastReceiver)
private fun getConnectivityStatus(): SealedNetworkState = if (connectivityManager.activeNetworkInfo?.isConnected == true) {
when (connectivityManager.activeNetworkInfo?.type) {
ConnectivityManager.TYPE_WIFI -> SealedNetworkState.NetworkWiFi
ConnectivityManager.TYPE_MOBILE -> SealedNetworkState.NetworkMobile
else -> SealedNetworkState.NetworkOther
}
} else SealedNetworkState.NetworkNone
private fun onReceive() = with(getConnectivityStatus()) {
if (this != stateLiveData.value) stateLiveData.postValue(this)
}
}
sealed class SealedNetworkState {
object NetworkWiFi : SealedNetworkState()
object NetworkMobile : SealedNetworkState()
object NetworkOther : SealedNetworkState()
object NetworkNone : SealedNetworkState()
}
答案 4 :(得分:0)
在Kotlin中,使用以下方法检查互联网是否可用:
private fun isOnline(): Boolean {
val connectivityManager =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
return true
}
}
}
return false
}
在没有互联网的情况下显示带有设置选项的小吃店:
private fun showNoNetSnackbar() {
val snack = Snackbar.make(rootView, "No Internet!", Snackbar.LENGTH_LONG) // replace root view with your view Id
snack.setAction("Settings") {
startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
}
snack.show()
}
启用WiFi后,然后在onResume中执行您想做的任何事情。