互联网即将到来时刷新活动

时间:2015-09-05 03:32:24

标签: android android-activity

当互联网出现时,我制作了一些代码来刷新 MainActivity 活动但是当我在活动中放入一些方法来进行刷新活动时,我遇到了问题,它总是向我返回null。 当互联网到来时,我从 InternetReceiver 类调用活动方法 upadetStateConnection

MainActivity

public class MainActivity extends ActionBarActivity {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
public void upadetStateConnection() {
        Intent intent = getIntent();///null 
        finish();
        startActivity(intent);
    }

检查连接的类是否来了:

public class InternetReceiver extends BroadcastReceiver {
    public void notificationStateInternet() {
        MainActivity kl= new MainActivity();
        kl.upadetStateConnection();
    }

    //check state internet
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfoWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo activeNetInfoMobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = (activeNetInfoWifi != null && activeNetInfoWifi.isConnectedOrConnecting()) || (activeNetInfoMobile != null && activeNetInfoMobile.isConnectedOrConnecting());
        Bundle bundle = new Bundle();
        bundle.putSerializable("MyData", true);
        if (isConnected) {
            notificationStateInternet();
            Log.i("NET", "connecte" + isConnected);
        } else {

            Log.i("NET", "not connecte" + isConnected);
        }
    }
} 

2 个答案:

答案 0 :(得分:0)

开始您的活动
{{1}}

答案 1 :(得分:0)

下面:

MainActivity kl= new MainActivity();
kl.upadetStateConnection();

这些行会导致问题,因为尝试通过创建扩展Activity的类的对象来访问方法,以及为什么getIntent()方法调用总是返回nullNullPointerException因为Context无效。< / p>

  

用于在互联网出现时刷新MainActivity活动的代码

InternetReceiver类作为MainActivity的内部类,然后从内部类调用upadetStateConnection方法,而不创建如下对象:

   public void notificationStateInternet() { 
        upadetStateConnection();
    }