完整代码以通过asynctask检查互联网连接

时间:2018-10-28 19:18:21

标签: java android android-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的新手。

library(shiny)

ui <- fluidPage(
  sidebarLayout(
  sidebarPanel(
    textInput("text", "Text to be searched")
  ),
  mainPanel(
     textOutput("textOut")
     )
  )
)

server <- function(input, output) {
wordlist <- c("a", "ab", "abc", "abcd", "abcde", "different")
# With pre-defined file
# wordlist <- read.delim("/path/to/the/file.txt", header = FALSE, sep = ",")
sublist <- NULL

newList <- reactive({
  if (input$text == ""){
    sublist <<- wordlist
  } else {
    temp <- sublist
    sublist <<- NULL
    sublist <<- temp[grepl(input$text, temp)]
  }
  sublist
})
output$textOut <- renderText({
 newList <- newList()
 cat(paste("Length of the sublist is: ", length(sublist), "\n"))
 newList
})
}

shinyApp(ui = ui, server = server)

还有我的Manifest.xml文件:-

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);

    }
  }
}

1 个答案:

答案 0 :(得分:0)

解决方案:有2个更正:

1。。删除此:

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

onCreate()的{​​{1}}内写上这个:

setContentView(...)

2。代替此:

this.context = SplashScreen.this;

写下:

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

然后:

从您的new CheckInternetAsyncTask(this.context).execute(); 中删除以下提到的代码,然后尝试断开wifi并运行该应用,它将显示。

onCreate(..)

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(...)

希望它能起作用。