判断手机联网状态

在Android应用开发中,为了确保用户体验,通常需要在启动时判断设备是否已联网。如果联网,直接展示主界面;否则,显示对话框让用户选择是否进入网络设置。本文通过实例展示了如何实现这一功能,包括布局、动画和判断联网状态的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发过程中,点击应用跳转到主界面时,对于需要联网才能用的设备而言,需要作出设备是否联网的判断,并且根据是否联网来确定下一步的操作,

如果联网了,则直接从动画进入主界面,否则弹出一个对话框 AlertDialog,来选择是否进入设置界面,进行网络连接操作。下面是一个实例:

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<ImageView 
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:src="@drawable/splash"
android:scaleType="fitXY"
   android:id="@+id/main_iv"/>


</LinearLayout>


anim文件夹下的动画文件:

<?xml version="1.0" encoding="utf-8"?>
<alpha
    android:fromAlpha="0.2"
    android:toAlpha="1.0"
    android:duration="3000"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true"
    xmlns:android="http://schemas.android.com/apk/res/android">
</alpha>


主要程序:

public class MainActivity extends Activity {
private ImageView iv;
private AlphaAnimation aa;
private AlertDialog.Builder ab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.main_iv);
aa = (AlphaAnimation) AnimationUtils.loadAnimation(this, R.anim.alpha_splash);
iv.setAnimation(aa);
aa.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub


}

@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
//判断设备是否联网
if(isConnected())//联网状态
{
}
else//非联网状态
{
ab = new Builder(MainActivity.this);
ab.setTitle("提示");
ab.setMessage("没有联网,请去设置");
ab.setPositiveButton("ok", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_SETTINGS);
startActivity(intent);
}
});
ab.setNegativeButton("cancel", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();
}
});
ab.create();
ab.show();
}
}
});
}
private boolean isConnected() {//判断是否联网的方法
// TODO Auto-generated method stub
boolean bo =false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni==null)
{
bo = false;
}
else
{
bo = ni.isConnected();
}
return bo;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值