java - 通过 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>
解决方案
解决方案:有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)
}
希望它有效。
推荐阅读
- r - R:webscraping 没有返回适用于“字符”类对象的“xml_find_all”的适用方法?
- python-3.x - Python3.8 socketserver.TCPServer 发送请求和处理请求之间的延迟
- android - 按下电源按钮时无法检测到何时释放音量
- python - 我正在研究梯度下降,在这个代码精度的含义是什么?
- typescript - 是否可以处理基于类型中的布尔值的有条件的可选属性?
- python - 除非我放大 Kivy 中的底部分隔栏,否则我的按钮不会响应;我该如何解决?
- reactjs - Next js中页面刷新时查询值丢失?
- java - JAVA将字符串从数组拆分成更小的数组以进入创建对象的方法?
- velo - 如何在 Wix.com 中隐藏嵌入式网站的 URL?
- ios - 未展示插页式广告(IOS;Swift)