Java 在android上从asynctask检查internet状态
我有两个班;第一个是Java 在android上从asynctask检查internet状态,java,android,android-asynctask,android-context,Java,Android,Android Asynctask,Android Context,我有两个班;第一个是asynctask,另一个是ConnectionDetector类 其中包含所示代码(第3步) 公共类myTask扩展了AsyncTask{ 私人语境; ConnectionDetector ConnectionDetector=新的ConnectionDetector(上下文); @凌驾 受保护的void onPreExecute(){ //TODO自动生成的方法存根 super.onPreExecute(); //检查互联网连接 if(connectiondetector
asynctask
,另一个是ConnectionDetector
类
其中包含所示代码(第3步)
公共类myTask扩展了AsyncTask{
私人语境;
ConnectionDetector ConnectionDetector=新的ConnectionDetector(上下文);
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
//检查互联网连接
if(connectiondetector.isConnectingToInternet()){//connectiondetector.java中的方法
//做点什么
}
}
当我运行此代码时,在if
语句中会出现空指针异常。
是因为上下文的关系,我该如何解决这个问题
从不同的活动(
partosrecord.class
)调用asynctask
类
myTask site = new myTask(this);
site.execute();
或者在异步任务上使用以下代码
public class myTask extends AsyncTask<String,Void,String>{
private Context context;
ConnectionDetector connectiondetector
public myTask(Context con)
{
context=con;
connectiondetector = new ConnectionDetector(context);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//CHECK INTERNET CONNECTION
if(connectiondetector.isConnectingToInternet()){ //method from connectiondetector.java
//do something }
}
公共类myTask扩展了AsyncTask{
私人语境;
连接检测器连接检测器
公共myTask(上下文con)
{
上下文=con;
connectiondetector=新的connectiondetector(上下文);
}
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
//检查互联网连接
if(connectiondetector.isConnectingToInternet()){//connectiondetector.java中的方法
//做点什么}
}
将上下文从活动类传递给oyur asynctask的构造函数
new myTask(ActivityName.this).execute(params);
在你的任务中
public class myTask extends AsyncTask<String,Void,String>{
ConnectionDetector connectiondetector
Context mcontext;
public myTask(Context context)
{
mcontext= context;
connectiondetector = new ConnectionDetector(mcontext);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(connectiondetector.isConnectingToInternet()){
//dosomething
}
}
公共类myTask扩展了AsyncTask{
连接检测器连接检测器
语境;
公共myTask(上下文)
{
mcontext=上下文;
connectiondetector=新的connectiondetector(mcontext);
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
if(connectiondetector.isConnectingToInternet()){
//剂量
}
}
我这样调用任务,new myTask(activityname.this).execute(string1,string2,string3);我得到的构造函数是未定义的lint error您需要在异步任务中定义构造函数。您这样做了吗?private myTask(上下文上下文){..}是asynctask类中没有错误,但我的activity.class在我告诉的行中显示错误u@user1910290使您的构造函数公开并try@user1910290您得到该错误是因为您的构造函数是私有的。将其公开,它应该可以工作。构造函数将没有返回类型。请删除void
public class myTask extends AsyncTask<String,Void,String>{
ConnectionDetector connectiondetector
Context mcontext;
public myTask(Context context)
{
mcontext= context;
connectiondetector = new ConnectionDetector(mcontext);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(connectiondetector.isConnectingToInternet()){
//dosomething
}
}