启动应用程序时,我只会看到白色屏幕约15秒钟。我认为这是因为asynctask仍试图在后台访问服务器,尽管该服务器当前不在线。有什么方法可以解决用户收到一条消息,指出正在尝试连接服务器或引入了时间限制的问题?
我已经建立了这个库,以便在应用程序的开头下载一个文件,如果该文件的最新版本大于当前安装的daas的最新版本,则该文件将存储在该数据库中,并在downloadAvailableDatabase()中下载(做最后一个)。
这是两个文件的重要部分:
MainActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialization();
DataManager.Initialization(context);
}
DataManager.java
public static void Initialization(Context context){
try {
if (isNetworkAvailable(context)){
files_path = Objects.requireNonNull(context.getExternalFilesDir("")).toString();
IntegerDownloadTask integerDownloadTask = new IntegerDownloadTask();
Integer database_version = getDatabaseVersion(context);
Integer available_database_version = integerDownloadTask.execute(database_version_download_url).get();
if (database_version < available_database_version){
downloadAvailableDatabase();
}
}
} catch (Exception e){
Log.i("Error", e.toString());
}
}
private static Integer getDatabaseVersion(Context context){
File versionFile = new File(files_path, database_version_filename);
if(versionFile.exists()){
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(versionFile));
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
br.close();
return Integer.parseInt(stringBuilder.toString());
}
catch (Exception e) {
try {
FileOutputStream stream = new FileOutputStream(versionFile);
stream.write("0".getBytes());
stream.close();
} catch (Exception ignored){}
return 0;
}
} else {
try {
FileOutputStream stream = new FileOutputStream(versionFile);
stream.write("0".getBytes());
stream.close();
} catch (Exception ignored){}
return 0;
}
}
private static void downloadAvailableDatabase(){
}
private static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
} catch (Exception e){
return false;
}
}
答案 0 :(得分:0)
您可以通过在活动中添加progressBar来实现 在您的活动xml文件中,添加以下代码:
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
然后在活动中的OnCreate函数中初始化progressBar并将可见性设置为可见
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialization();
progressbar=findViewById(R.id.simpleProgressBar)
progressbar.setVisibility(View.VISIBLE)
DataManager.Initialization(context);
}
然后在异步任务中将progressBar的可见性设置为onPostExecute方法