java android:从非扩展活动类调用的 getSystemService 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17178941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
android: getSystemService calling from a non extended activity class not working
提问by Luther
I'm trying to test the internet connection of my app, and I'm testing it with "ConnectivityManager".
我正在尝试测试我的应用程序的互联网连接,我正在使用“ConnectivityManager”进行测试。
I'would like to call the ConnectivityManager class not from the main class, but from a class a made just to handel the connectivity test.
我不想从主类中调用 ConnectivityManager 类,而是从一个只是为了处理连接性测试而制作的类。
the method "getSystemService" in the second class gives me an error, how come???
第二个类中的方法“getSystemService”给我一个错误,怎么会???
This is the main class calling the connectivitymanager class:
这是调用connectivitymanager类的主类:
public void onClick(View v){
Log.d("mytag", "in onclick");
CheckInternetpermission obCheckInternetPermission= new CheckInternetpermission();
Log.d("mytag", "starting permission");
obCheckInternetPermission.check();
}
This is the connectivitymanager, "getSystemService" gives me this error: Cannot resolve method 'getSystemService(java.lang.String)
这是连接管理器,“getSystemService”给了我这个错误:Cannot resolve method 'getSystemService(java.lang.String)
package com.example.network;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.View;
public class CheckInternetpermission{
public void check(){
Log.d("mytag", "In check");
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE); //<---getSystemService give me error??????
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.d("mytag", "Internet connection TRUE");
} else {
Log.d("mytag","Internet connection FALSE"); // display error
}
}
}
回答by CommonsWare
getSystemService()
is a method on Context
. You need to have a Context
to obtain a system service. Your Activity
, for example, is a Context
, as the Activity
class inherits from Context
.
getSystemService()
是一种方法Context
。你需要有一个Context
来获取系统服务。你的Activity
,例如,是Context
作为Activity
从类继承Context
。