如何使(没有Internet连接)broadCastReceiver可以进行所有活动

时间:2019-01-04 11:19:42

标签: android broadcastreceiver

我正在使用ConnectivityManager检查Internet连接,问题是,启用Internet时我无法重新启动活动,并且我无法显示所有活动中的错误消息(没有Internet连接)。以下是我的代码

  ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if(!(networkInfo!=null && networkInfo.isConnected())){
      Intent i = new Intent(this,NoInternetConnection.class);
      startActivity(i);
    }

对于NoInternetConnection类,我的编码如下所示

 public class NoInternetConnection extends AppCompatActivity {
private static ImageView internetStatus;
private static TextView noConnectionText;
private static Button tryAgain;
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final ActionBar actionBar =getSupportActionBar();
    actionBar.hide();
    setContentView(R.layout.activity_no_internet_connection);
    internetStatus = (ImageView) findViewById(R.id.internetStatus);
    noConnectionText=(TextView)findViewById(R.id.noConnectionText);
    tryAgain=(Button)findViewById(R.id.tryAgain);
    tryAgain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //checking internet connection
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (!(networkInfo != null && networkInfo.isConnected())) 
            {
              onRestart();
            }
            else {
                finish();
            }
        }
    });
    internetStatus.setImageResource(R.drawable.img);
    noConnectionText.setText("No Internet Connection");
 }
}

1 个答案:

答案 0 :(得分:0)

创建此类

public class Utils{

public static void startActivity(Context context,Class clas,Bundle extras)
    {
        ConnectivityManager connectivityManager = 
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(!(networkInfo!=null && networkInfo.isConnected())){
            Intent i = new Intent(context,NoInternetConnection.class);
            context.startActivity(i);
        }else {
            Intent i = new Intent(context,clas);
            i.putExtras(extras);
            context.startActivity(i);
        }
    }
}

,并且每当您需要启动活动而不是调用

Intent i = new Intent(this,YourActivity.class);
startActivity(i);

致电Utils.startActivity(context,YourActivity.class,new Bundle());