Java tutorial
package ru.for_inform.we_recommend.view; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import com.android.volley.Request; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import ru.for_inform.we_recommend.R; import ru.for_inform.we_recommend.model.MyApp; import ru.for_inform.we_recommend.model.MyUser; import ru.for_inform.we_recommend.model.PhoneBook_Contact; import ru.for_inform.we_recommend.model.RootHashTag; import ru.for_inform.we_recommend.model.MyRequest; import ru.for_inform.we_recommend.model.TagColor; /** * Created by OS1 on 29.04.2016. */ public class Loading_Activity extends Activity implements View.OnClickListener, MyRequest.OnResponseReturnListener, ActivityCompat.OnRequestPermissionsResultCallback { private Context context; private SharedPreferences shPref; private MyRequest myRequest; private final int notAgreeTVResId = R.id.LicenseDialog_NotAgreeTV; private final int agreeTVResId = R.id.LicenseDialog_AgreeTV; private TextView notAgreeTV; private TextView agreeTV; private AlertDialog.Builder errorDialog; private Dialog licenseDialog; private Handler handler; private LoadingTask loadingTask; private final int AUTHORIZE = 2; private final int SHOW_LICENSE = 3; private final int APP_ERROR = 4; private final int REQUEST_CODE_ASK_PERMISSIONS = 115; // private final String LOG_TAG = "myLogs"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // - ? setContentView(R.layout.loading_layout); ////////////////////////////////////////////////////////////////////////////////// // ? context = this; ////////////////////////////////////////////////////////////////////////////////// // ? ? Preferences shPref = getSharedPreferences("user_data", MODE_PRIVATE); // Preferences loadTextFromPreferences(); ////////////////////////////////////////////////////////////////////////////////// handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case AUTHORIZE: // ?? ? ? ? authorize(); break; case SHOW_LICENSE: // " ? ?" showLicenseDialog(); break; case APP_ERROR: // ?? , showErrorDialog(R.string.get_user_id_error, true); break; } } }; ////////////////////////////////////////////////////////////////////////////////// // ? ? ? ? myRequest = new MyRequest(context); } @Override protected void onResume() { super.onResume(); loadingTask = new LoadingTask(); loadingTask.execute(); } @Override public void onClick(View v) { switch (v.getId()) { // ? "? ??" case notAgreeTVResId: // ?? MyUser.setAgreeWithAppLicense(false); // ?? Preferences saveTextInPreferences("user_license_agree", "N"); // ? ? ? notAgreeTV.setBackgroundResource(R.color.light_brown); notAgreeTV.setTextColor(getResources().getColor(R.color.white)); // " ? ?" closeLicenseDialog(); // finish(); break; // ? "C?" case agreeTVResId: // ?? MyUser.setAgreeWithAppLicense(true); // ?? Preferences saveTextInPreferences("user_license_agree", "Y"); // ? ? ? agreeTV.setBackgroundResource(R.color.light_brown); agreeTV.setTextColor(getResources().getColor(R.color.white)); // " ? ?" closeLicenseDialog(); // ? ? createUser(); break; } } // @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { // ? ? ? case REQUEST_CODE_ASK_PERMISSIONS: // ? ? if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // ?? ? setUserContacts(); // - getRootTags(); } // ? ? else // - getRootTags(); break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } // public void onResponseReturn(JSONObject serverResponse) { // ? ? ? if (serverResponse != null) { try { String requestType = ""; String responseType = ""; // ? ? ? "requestType" if (serverResponse.has("requestType")) // " ?" requestType = serverResponse.getString("requestType"); // ? ? ? "responseType" if (serverResponse.has("responseType")) // " " responseType = serverResponse.getString("responseType"); // ? " ?" if ((requestType != null) && (!requestType.equals(""))) { JSONObject dataObject = null; JSONArray dataArray = null; // ? " " if ((responseType != null) && (!responseType.equals(""))) { // ? ? ?? ? String message = ""; // ? " " - JSONObject if (responseType.equals("JSONObject")) { // ? ? ? "data" if (serverResponse.has("data")) { // JSONObject dataObject = serverResponse.getJSONObject("data"); // ? JSONObject ? "message" if ((dataObject != null) && (dataObject.has("message"))) // message = dataObject.getString("message"); } } // ? " " - JSONArray else if (responseType.equals("JSONArray")) { // ? ? ? "data" if (serverResponse.has("data")) // JSONArray dataArray = serverResponse.getJSONArray("data"); } /////////////////////////////////////////////////////////////////////////////// // ? " ?" - "??" if (requestType.equals("authorize")) { // ? ? ? if ((message != null) && (!message.equals(""))) { // ? ? ? - " " if (message.equals(getResources().getString(R.string.authorize_success))) { // ? ? ? ? if (MyUser.getId().equals("")) { // ? JSONObject ? "id" if (dataObject.has("id")) { // String userIdStr = dataObject.getString("id"); // ? if (userIdStr != null) { // ?? MyUser.setId(userIdStr); // ?? Preferences saveTextInPreferences("user_id", userIdStr); } } // ? JSONObject ? ? "id" else // ?? , showErrorDialog(R.string.server_error, true); } // ? JSONObject ? "access_token" if (dataObject.has("access_token")) { // String user_access_token = dataObject.getString("access_token"); // ?? MyUser.setAccessToken(user_access_token); // ?? Preferences saveTextInPreferences("user_access_token", user_access_token); //////////////////////////////////////////////////////////// // ? , ? grantToReadContacts(); } // ? JSONObject ? ? "access_token" else // ?, showErrorDialog(R.string.server_error, true); } // ? ? ? - " " else if (message.equals(getResources().getString(R.string.authorize_error))) // ?, showErrorDialog(R.string.get_user_id_error, true); // ? ? ? ? else // ?? , showErrorDialog(R.string.server_error, true); } // ? ? ? ? else // ?? , showErrorDialog(R.string.server_error, true); } // ? " ?" - "" else if (requestType.equals("rootTags")) { // ? JSONArray if ((dataArray != null)) { // - - JSONArray int rootHashTagsSum = dataArray.length(); // ? JSONArray ? if (rootHashTagsSum > 0) { // Map<String, RootHashTag> rootHashTagsMap = new HashMap<>(); // JSONArray for (int i = 0; i < rootHashTagsSum; i++) { // ? dataArray JSONObject rootHashTagJSONObj = (JSONObject) dataArray.get(i); // - String rootHashTagIdStr = rootHashTagJSONObj.getString("id"); String rootHashTagNameStr = rootHashTagJSONObj.getString("name"); //////////////////////////////////////////////////////////// // ? " " TagColor tagColor = new TagColor(i, MyApp.getRootTagBgColor(i)); //////////////////////////////////////////////////////////// // ? ? if ((rootHashTagIdStr != null) && (rootHashTagNameStr != null)) { // ? ? ? if ((!rootHashTagIdStr.equals("")) && (!rootHashTagNameStr.equals(""))) { // ? " -" RootHashTag rootHashTag = new RootHashTag(rootHashTagIdStr, rootHashTagNameStr, tagColor); ///////////////////////////////////////////////////////////////////////////// // StringBuilder rootHashTagsMapKeySB = new StringBuilder(""); // ? 10 if (i < 10) // ? 0, ? ? rootHashTagsMapKeySB.append("0"); // ? rootHashTagsMapKeySB.append("" + i); ///////////////////////////////////////////////////////////////////////////// // ? - rootHashTagsMap.put(rootHashTagsMapKeySB.toString(), rootHashTag); } } } // ?? MyApp.setAppRootHashTagsMap(rootHashTagsMap); // ? ? ? ?? if (!MyApp.isAppRootHashTagsMapEmpty()) // " ?" moveForward(); // ? ? ? ?? else // ?? , showErrorDialog(R.string.server_error, true); } // ? JSONArray ? else // ?? , showErrorDialog(R.string.server_error, true); } // ? JSONArray else // ?? , showErrorDialog(R.string.server_error, true); } // ? " ?" - "??" else if (requestType.equals("signup")) { // ? ? ? if ((message != null) && (!message.equals(""))) { // ? ? ? - "?? ?." if (message.equals(getResources().getString(R.string.signup_success))) { // ? JSONObject if ((dataObject != null)) { // ? JSONObject ? "access_token" if (dataObject.has("access_token")) { // MyUser.setAccessToken(dataObject.getString("access_token")); // ?? authorize(); } // ? JSONObject ? ? "access_token" else // ?? , showErrorDialog(R.string.server_error, true); } // ? JSONObject else // ?? , showErrorDialog(R.string.server_error, true); } // ? ? ? ? else // ?? , showErrorDialog(R.string.server_error, true); } // ? ? ? ? else // ?? , showErrorDialog(R.string.server_error, true); } } } } catch (JSONException e) { e.printStackTrace(); // ?? , showErrorDialog(R.string.server_error, true); } } else // ?? , showErrorDialog(R.string.server_error, true); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void authorize() { // ? ? Map<String, String> requestBody = new HashMap<>(); requestBody.put("accessToken", MyUser.getAccessToken()); // ? ? ? MyApp.sendRequest(myRequest, Request.Method.POST, "site/login-mobile", null, "authorize", null, requestBody); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void showLicenseDialog() { // ? " ? ??" licenseDialog = new Dialog(context, R.style.InfoDialog_Theme); licenseDialog.setContentView(R.layout.license_dialog_layout); licenseDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); // "? ??" notAgreeTV = (TextView) licenseDialog.findViewById(notAgreeTVResId); notAgreeTV.setOnClickListener(Loading_Activity.this); // "?" agreeTV = (TextView) licenseDialog.findViewById(agreeTVResId); agreeTV.setOnClickListener(Loading_Activity.this); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // "? ? " final ScrollView scrollViewSV = (ScrollView) licenseDialog.findViewById(R.id.LicenseDialog_ScrollViewSV); // ? ? ? ?? TextView licenseTextTV = new TextView(context); licenseTextTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); licenseTextTV.setTextSize(8); licenseTextTV.setTextColor(context.getResources().getColor(R.color.black)); licenseTextTV.setText(getAssetData(R.string.license_path)); setPaddings(licenseTextTV, 10, 0, 10, 0); // ? ? ? scrollViewSV.addView(licenseTextTV); // ? licenseDialog.show(); } // ? private void showErrorDialog(int resId, final boolean closeApp) { // ? ? errorDialog = new AlertDialog.Builder(context); // ? ?? errorDialog.setTitle(getResources().getString(R.string.error)); // errorDialog.setMessage(getResources().getString(resId)); // ? errorDialog.setPositiveButton(context.getResources().getString(R.string.ok_text), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { // ? ? ?? if (closeApp) // finish(); } }); errorDialog.setCancelable(true); errorDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { } }); // errorDialog.show(); } //////////////////////////////////////////////////////////////////////////////////////////////// // ? ?? private String getAssetData(int resId) { // ? ?? String str_data = new String(); byte[] buffer = null; InputStream is; try { // , ? is = getAssets().open(context.getResources().getString(resId)); // ? ?? int size = is.available(); // ?? buffer = new byte[size]; // ? ?? is.read(buffer); // is.close(); } catch (IOException e) { e.printStackTrace(); } // ? ? if (buffer != null) // ? str_data = new String(buffer); // return str_data; } //////////////////////////////////////////////////////////////////////////////////////////////// // private void closeLicenseDialog() { // ? " ? ?" if (licenseDialog != null) // licenseDialog.dismiss(); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void moveForward() { // ? "? ?" Intent intent = new Intent(Loading_Activity.this, RootHashTag_Activity.class); startActivity(intent); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void createUser() { // ? ? Map<String, String> requestBody = new HashMap<>(); requestBody.put("signupToken", getResources().getString(R.string.signup_token)); // ? ? ? MyApp.sendRequest(myRequest, Request.Method.POST, "site/signup-mobile", null, "signup", null, requestBody); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void sendContacts() { // ?? ? Map<String, PhoneBook_Contact> contactsMap = MyUser.getContactsMap(); // ? Set<String> contactsMapKeysSet = contactsMap.keySet(); // ? ?? ? ? List<String> contactsMapKeysList = new ArrayList<>(); // ? if (contactsMapKeysSet != null) // ? ?? contactsMapKeysList.addAll(contactsMapKeysSet); // ? ?? Collections.sort(contactsMapKeysList); //////////////////////////////////////////////////////////////////////////////////////// // ? ? Map<String, String> requestBody = new HashMap<>(); // ?? for (int i = 0; i < contactsMapKeysList.size(); i++) { // PhoneBook_Contact contact = contactsMap.get(contactsMapKeysList.get(i)); String phone = contact.getPhoneNumber(); String phoneCrypted = contact.getPhoneNumberCrypted(); // ?, ? ?? // requestBody.put("phones[" + i + "]", phonesList.get(i)); requestBody.put("phones[" + i + "]", phone); Log.d("myLogs", "{" + i + "} - phone= " + phone + ", phoneCrypted= " + phoneCrypted); } //////////////////////////////////////////////////////////////////////////////// // ? ? ? MyApp.sendRequest(myRequest, Request.Method.POST, "site/sync-mobile-phones", "?", "synchronization", new String[] { "token=" + MyUser.getAccessToken() }, requestBody); } // private void grantToReadContacts() { // ? ?? ? 23 (Marshmallow+) if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // ? ? ? () int hasReadContactsPermission = ContextCompat.checkSelfPermission(Loading_Activity.this, Manifest.permission.READ_CONTACTS); // ? ? if (hasReadContactsPermission != PackageManager.PERMISSION_GRANTED) { // ? ? ? ? ActivityCompat.requestPermissions(Loading_Activity.this, new String[] { Manifest.permission.READ_CONTACTS }, REQUEST_CODE_ASK_PERMISSIONS); } } // ? ?? ? 23 (Pre-Marshmallow) else { // ?? ? setUserContacts(); // - getRootTags(); } } // private void setUserContacts() { try { // ? ? Cursor cursor = getContacts(); // ? ? if (cursor != null) { // ? ? ? if (cursor.getCount() > 0) { // Map<String, PhoneBook_Contact> contactsMap = new HashMap<>(); // ? int contactMapKey = 0; // ? while (cursor.moveToNext()) { // ? String name = cursor.getString(1); // String phone = cursor.getString(2); // ? ? if ((name != null) && (!name.equals("")) && (phone != null) && (!phone.equals(""))) { // ? ? ? ? if (phone.indexOf("+") != -1) // ? phone = phone.replace("+", ""); // ? ? ? ? if (phone.indexOf("(") != -1) // ? phone = phone.replace("(", ""); // ? ? ? ? if (phone.indexOf(")") != -1) // ? phone = phone.replace(")", ""); // ? ? ? ? if (phone.indexOf("-") != -1) // ? phone = phone.replace("-", ""); // ? ? ? ? if (phone.indexOf(":") != -1) // ? phone = phone.replace(":", ""); // ? ? ? ? if (phone.indexOf("/") != -1) // ? phone = phone.replace("/", ""); // ? ? ? ? if (phone.indexOf(",") != -1) // ? phone = phone.replace(",", ""); // ? ? ? ? if (phone.indexOf(" ") != -1) // ? phone = phone.replace(" ", ""); //////////////////////////////////////////////////////////////////// // ? 10 int startPos = (phone.length() - 10); int endPos = phone.length(); String phoneNumber = phone.substring(startPos, endPos); // ? "" // PhoneBook_Contact userContact = new PhoneBook_Contact(phone.substring(startPos, endPos), name); PhoneBook_Contact userContact = new PhoneBook_Contact(phoneNumber, MyApp.getCrypted(phoneNumber), name); //////////////////////////////////////////////////////////////////// // StringBuilder contactMapKeySB = new StringBuilder(""); // ? 10 if (contactMapKey < 10) // ? 0, ? contactMapKeySB.append("0"); // ? contactMapKeySB.append(contactMapKey); // contactsMap.put(contactMapKeySB.toString(), userContact); // 1 contactMapKey++; } } // ?? ? MyUser.setContactsMap(contactsMap); // ? ? ? if (!MyUser.isContactsMapEmpty()) // ? ? sendContacts(); } } } catch (Exception exc) { // showErrorDialog(R.string.no_contacts_list_access, false); } } // private Cursor getContacts() { Cursor cursor = null; try { // cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }, null, null, null); startManagingCursor(cursor); } catch (Exception exc) { // showErrorDialog(R.string.no_contacts_list_access, false); } // return cursor; } //////////////////////////////////////////////////////////////////////////////////////////////// // private void getRootTags() { // ? ? - ( ) MyApp.sendRequest(myRequest, Request.Method.GET, "tags", "?", "rootTags", new String[] { "tag_id=null" }, null); } //////////////////////////////////////////////////////////////////////////////////////////////// // private void setPaddings(View view, int left, int top, int right, int bottom) { float density = context.getResources().getDisplayMetrics().density; int paddingLeft = (int) (left * density); int paddingTop = (int) (top * density); int paddingRight = (int) (right * density); int paddingBottom = (int) (bottom * density); view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); } //////////////////////////////////////////////////////////////////////////////////////////////// /** * ? Preferences * @param field - * @param value - */ private void saveTextInPreferences(String field, String value) { SharedPreferences.Editor ed = shPref.edit(); ed.putString(field, value); ed.commit(); } /** * ? Preferences */ private void loadTextFromPreferences() { // ? Preferences ? if (shPref.contains("user_id")) // MyUser.setId(shPref.getString("user_id", "")); // ? Preferences ? if (shPref.contains("user_access_token")) // MyUser.setAccessToken(shPref.getString("user_access_token", "")); // ? Preferences ? if (shPref.contains("user_license_agree")) { // String userAnswer = shPref.getString("user_license_agree", ""); // ? ???? ? ? if (userAnswer.equals("Y")) // ? ? MyUser.setAgreeWithAppLicense(true); } } //////////////////////////////////////////////////////////////////////////////////////////////// class LoadingTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { try { // "?" 5 ? TimeUnit.SECONDS.sleep(5); // ? ? if (!MyUser.getId().equals("")) // ? ? "??" handler.sendEmptyMessage(AUTHORIZE); // ? ? ? else { // ? ??? if (!MyUser.isAgreeWithAppLicense()) // ? ? "??" handler.sendEmptyMessage(SHOW_LICENSE); } } catch (Exception exc) { exc.printStackTrace(); // handler.sendEmptyMessage(APP_ERROR); } return null; } } }