首页 > 解决方案 > 通过 asynctask 检查互联网连接的完整代码

问题描述

我收到错误:-

java.lang.RuntimeException: 无法实例化活动 ComponentInfo{com.example.juhi_gupta.pizza_corner/com.example.juhi_gupta.pizza_corner.SplashScreen}: java.lang.InstantiationException: java.lang.Class 没有零参数构造函数

我的代码出了什么问题?我是 Asynctask 的新手。

public class SplashScreen extends Activity {

Context context;

SplashScreen(Context context)
{
    this.context = context;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    int SPLASH_TIME_OUT = 3000;
    new Handler().postDelayed(new Runnable() {

        /*
         * Showing splash screen with a timer. This will be useful when you
         * want to show case your app logo / company
         */

        @Override
        public void run() {
            // This method will be executed once the timer is over
            // Start your app main activity
            Intent i = new Intent(SplashScreen.this, LoginActivity.class);
            startActivity(i);
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

            // close this activity
            finish();
        }
    }, SPLASH_TIME_OUT);

    if (isNetworkAvailable()) {
        new CheckInternetAsyncTask(getApplicationContext()).execute();
    }
    else {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("No Internet Connection");
        alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(getApplicationContext(), "Please check your internet connection and try again", Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}

@SuppressLint("StaticFieldLeak")
class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {

    private Context context;

    CheckInternetAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(Void... params) {

        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        assert cm != null;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();

        if (isConnected) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                        (new URL("http://clients3.google.com/generate_204")
                                .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                if (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0)
                    return true;

            } catch (IOException e) {
                Log.e("TAG", "Error checking internet connection", e);
                Toast.makeText(getApplicationContext(), "Error checking internet connection", Toast.LENGTH_LONG).show();
                return false;
            }
        } else {
            Log.d("TAG", "No network available!");
            Toast.makeText(getApplicationContext(), "No network available!", Toast.LENGTH_LONG).show();
            return false;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        Log.d("TAG", "result" + result);

    }
  }
}

还有我的 Manifest.xml 文件:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.juhi_gupta.pizza_corner">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >

        <!-- Splash screen -->
        <activity
            android:name="com.example.juhi_gupta.pizza_corner.SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

标签: javaandroidandroid-asynctask

解决方案


解决方案:有2个更正:

1.删​​除这个:

SplashScreen(Context context)
{
    this.context = context;
}

改写这个,在你onCreate()的行之后setContentView(...)

this.context = SplashScreen.this;

2.取而代之的是:

new CheckInternetAsyncTask(getApplicationContext()).execute();

写这个:

new CheckInternetAsyncTask(this.context).execute();

然后:

从您中删除下面提到的代码onCreate(..)并尝试断开您的 wifi 并运行应用程序,它会显示。

int SPLASH_TIME_OUT = 3000;
new Handler().postDelayed(new Runnable() {

    /*
     * Showing splash screen with a timer. This will be useful when you
     * want to show case your app logo / company
     */

    @Override
    public void run() {
        // This method will be executed once the timer is over
        // Start your app main activity
        Intent i = new Intent(SplashScreen.this, LoginActivity.class);
        startActivity(i);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

        // close this activity
        finish();
    }
}, SPLASH_TIME_OUT);

在里面写上上面的代码onPostExecute(...)

@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);
    Log.d("TAG", "result" + result);

    ...... (Over Here)

}

希望它有效。


推荐阅读