本文介绍了开创了机器人全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要做的就是创建一个具有多种功能,我想在整个项目中使用它的Java文件。例如检查Internet连接。然后,我想呼吁每个活动的功能。有谁知道该怎么做?
What i want to do is create a java file that has various functions and I would like to use it across the whole project. For example check Internet Connection. Then I would like to call that function on each activity. Does anyone know how to do that?
推荐答案
创建类像这样的在这里添加的功能:
Create Class like this and add your functions here :
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;
}
}
然后在你的活动声明实例:
Then declare instance in your activity :
MyGlobals myGlog;
然后初始化并从全局类的使用方法:
Then initialize and use methods from that global class :
myGlog = new MyGlobals(getApplicationContext());
String username = myGlog.getUserName();
boolean inConnected = myGlog.isNetworkConnected();
在你的清单文件所需的权限:
Permission required in your Manifest file :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
感谢。
这篇关于开创了机器人全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!