当互联网出现时,我制作了一些代码来刷新 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);
}
}
}
答案 0 :(得分:0)
以
开始您的活动{{1}}
答案 1 :(得分:0)
下面:
MainActivity kl= new MainActivity();
kl.upadetStateConnection();
这些行会导致问题,因为尝试通过创建扩展Activity的类的对象来访问方法,以及为什么getIntent()
方法调用总是返回null
或NullPointerException
因为Context无效。< / p>
用于在互联网出现时刷新MainActivity活动的代码
将InternetReceiver
类作为MainActivity
的内部类,然后从内部类调用upadetStateConnection
方法,而不创建如下对象:
public void notificationStateInternet() {
upadetStateConnection();
}