Android判断手机是否联网及自动跳转功能(收藏版

编辑: admin 分类: 安卓教程 发布时间: 2022-03-14 来源:互联网

android欢迎页自动跳转及手机网络检测,具体实现代码如下所示:

在1.2s后从欢迎页(welcome)跳转到登陆页(Login_Activity),并进行手机网络检测

在这里插入图片描述

在这里插入图片描述

package com.example.amusic.welcome;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.amusic.monitor.NetworkChangeReceiver;
import com.example.amusic.R;
import java.util.Timer;
import java.util.TimerTask;
public class welcome extends AppCompatActivity {
  private final int SKIP_DELAY_TIME = 1200;
  private NetworkChangeReceiver networkChangeReceiver;
  private IntentFilter intentFilter;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    //手机网络检测
    intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    networkChangeReceiver = new NetworkChangeReceiver();
    registerReceiver ( networkChangeReceiver, intentFilter);
    Timer time = new Timer();
    TimerTask task = new TimerTask(){
      @Override
      public void run() {
        startActivity(new Intent(welcome.this,Login_Activity.class));
        finish();
        //onDestroy();
      }
    };
    time.schedule(task, SKIP_DELAY_TIME);
  }
  protected void onDestroy(){
    super.onDestroy();
    unregisterReceiver( networkChangeReceiver);
  }
}
// An highlighted block
var foo = 'bar';

public class NetworkChangeReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectivityManager = (ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo!= null&&networkInfo.isAvailable()) {
      Toast.makeText(context, "手机网络已开启!", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(context, "手机网络未开启!", Toast.LENGTH_SHORT).show();
    }

  }

}
// An highlighted block
var foo = 'bar';

运行结果

在这里插入图片描述

总结

以上所述是小编给大家介绍的Android判断手机是否联网及自动跳转功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对海外IDC网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!