解决方法
像这样创建类并在此处添加您的函数:
package com.mytest; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class MyGlobals{ Context mContext; // constructor public MyGlobals(Context context){ this.mContext = context; } public String getUserName(){ return "test"; } public boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { // There are no active networks. return false; } else return true; } }
然后在您的活动中声明实例:
MyGlobals myGlog;
然后初始化并使用该全局类中的方法:
myGlog = new MyGlobals(getApplicationContext()); String username = myGlog.getUserName(); boolean inConnected = myGlog.isNetworkConnected();
您的清单文件中所需的权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
谢谢.