Java tutorial
package com.android.projectz.teamrocket.thebusapp.activities; /* Copyright (C) 2016-2017 TeamRocket This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import android.Manifest; import android.app.DownloadManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.v13.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.android.projectz.teamrocket.thebusapp.IntroApp; import com.android.projectz.teamrocket.thebusapp.R; import com.android.projectz.teamrocket.thebusapp.local.DbAdapter; import com.android.projectz.teamrocket.thebusapp.settings.SettingGeneralActivity; import com.android.projectz.teamrocket.thebusapp.util.Cryptography; import com.android.projectz.teamrocket.thebusapp.util.Device; import com.android.projectz.teamrocket.thebusapp.util.SharedPreferencesUtils; import com.android.volley.AuthFailureError; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Time; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * SplashScreenActivity: * quasta funzione ha il compito di avviare tutta l'app, inoltre ha il compito di: * 1-controllare la connessione(funzione boolean che ritorna true=>connessione stabilita/false=>connessione assente) * 2-controllo con il database, se il db online (funzione boolean che ritorna true=>db online/false=>db offline * inoltre questa classe deve risolvere tutti i problemi legati a file di config * ecc... * * @author simone98dm, moreno98 * @data 04/11/2016 */ public class SplashScreenActivity extends AppCompatActivity { private String TAG = SplashScreenActivity.class.getSimpleName(); private String[] permissions = { android.Manifest.permission.INTERNET, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.GET_ACCOUNTS }; /** * Questo metodo crea la splashscreen */ @Override protected void onCreate(Bundle savedInstanceState) { this.setTheme(getResources().getIdentifier(SharedPreferencesUtils.getSelectedTheme(this), "style", getPackageName())); super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); } @Override protected void onStart() { super.onStart(); if (SharedPreferencesUtils.isTheFirstRun(SplashScreenActivity.this)) { setLanguage("system"); //---[avvio della intro]--- Intent intent = new Intent(SplashScreenActivity.this, IntroApp.class); startActivity(intent); finish(); return; } else { setLanguage("local"); } SharedPreferencesUtils.setWebsiteUrl(this, "http://rocketeam.altervista.org"); checkAndRequestPermissions(); if (checkAndRequestPermissions() == true) { if (checkConnectionToInternet() == true) { if (checkConnectionToServer() == true) { startMainActivity(); } else { } } else { showErrorDialog(getResources().getString(R.string.error_server_connection), "checkAll"); } } else { showErrorDialog(getResources().getString(R.string.error_internet_connection), "checkAll"); } } public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; private boolean checkAndRequestPermissions() { int internet = ContextCompat.checkSelfPermission(this, permissions[0]); int w_ext = ContextCompat.checkSelfPermission(this, permissions[1]); int account = ContextCompat.checkSelfPermission(this, permissions[2]); int r_phone = ContextCompat.checkSelfPermission(this, permissions[3]); List<String> listPermissionsNeeded = new ArrayList<>(); Log.d(TAG, "internet: " + internet); Log.d(TAG, "w_ext: " + w_ext); Log.d(TAG, "account: " + account); Log.d(TAG, "r_phone: " + r_phone); if (internet != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(permissions[0]); } if (w_ext != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(permissions[1]); } if (account != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(permissions[2]); } if (r_phone != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(permissions[3]); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } public void showErrorDialog(String content, final String command) { if (command.equals("exit")) { new MaterialDialog.Builder(SplashScreenActivity.this).title(R.string.error_title).content(content) .cancelable(false).positiveText(R.string.dialog_ok_button) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { finish(); startActivity(new Intent(Intent.ACTION_UNINSTALL_PACKAGE, Uri.parse("package:com.android.teamrocket.thebusproject.thebusapp"))); System.exit(0); } }).show(); } else { new MaterialDialog.Builder(SplashScreenActivity.this).title(R.string.error_title).content(content) .cancelable(false).positiveText(R.string.dialog_ok_button) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { if (command.contains("credentials")) { onStart(); } else if (command.contains("checkAll")) { onStart(); } else if (command.contains("retry")) { onStart(); } } }).negativeText(R.string.dialog_exit_button) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { System.exit(0); } }).show(); } } /** * Metodo che prende la lingua di sistema o quella delle SharedPreferences a seconda * della tipologia di avvio dell'app (se la prima volta quella di sistema, se non la * prima volta allora prende quella delle sharedpreferences) */ private void setLanguage(String type) { Locale language = null; if (type.equals("system")) { language = Locale.getDefault(); SharedPreferencesUtils.setSelectedLanguage(this, Locale.getDefault().getLanguage()); } else if (type.equals("local")) { String languageToLoad = SharedPreferencesUtils.getSelectedLanguage(this); language = new Locale(languageToLoad); Locale.setDefault(language); } Configuration config = new Configuration(); config.locale = language; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } /** * permette di capire se il server esterno attualmente disponibile oppure offline * * @return boolean che identifica se il server online o offline */ private boolean checkConnectionToServer() { if (android.os.Build.VERSION.SDK_INT > 9) { //questo per i permessi OBBLIGATORIO StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } URL url = null; HttpURLConnection urlConnection = null; try { url = new URL(SharedPreferencesUtils.getWebsiteUrl(this) + "/app/altra_prova.php"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { urlConnection.disconnect(); return true; } return false; } catch (IOException e) { e.printStackTrace(); if (!SharedPreferencesUtils.getWebsiteUrl(this).equals("http://thebusapp.orgfree.com")) { urlConnection.disconnect(); SharedPreferencesUtils.setWebsiteUrl(this, "http://thebusapp.orgfree.com"); checkConnectionToServer(); } return false; } } /** * controlla se il dispositivo connesso ad internet * * @return */ private boolean checkConnectionToInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } /** * permette di avviare l'activity main */ public void startMainActivity() { Intent mainIntent = new Intent(SplashScreenActivity.this, MainActivity.class); startActivity(mainIntent); finish(); } }