package com.qh.androiddemo;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.StrictMode;
import android.renderscript.Int2;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.qh.androiddemo.util.ConfigUtil;
import com.qh.androiddemo.util.SoapUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
import static android.R.attr.id;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
// Toast.makeText(getApplicationContext(), "登录失败!", Toast.LENGTH_LONG).show();
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
ConfigUtil configUtil;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
//获得实例对象
sp = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE);
if(sp.getBoolean("AUTO_ISCHECK", true))
{
//跳转界面
Intent intent = new Intent(LoginActivity.this,index.class);
LoginActivity.this.startActivity(intent);
}
configUtil=new ConfigUtil(this);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
public void reg(View v) {
Intent intent=new Intent(LoginActivity.this,RegActivity.class);
startActivity(intent);
}
public void wjmm(View v){
Intent intent=new Intent(LoginActivity.this,PasswordActivity.class);
startActivity(intent);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return ;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
login();
}
}
private void login(){
String endPort = "cre_ServicePort";
String method="loginb_service";
Object[] objects=new Object[]{
mEmailView.getText().toString(),
mPasswordView.getText().toString()
};
SoapUtil soapUtil = new SoapUtil();
Object object = soapUtil.connect(endPort,method,objects);
if(object.toString()!=null){
// configUtil.setUserJson(object.toString());
//记住用户名、密码、
SharedPreferences.Editor editor = sp.edit();
editor.putString("USER_NAME", object.toString());
editor.putBoolean("AUTO_ISCHECK", true);
editor.commit();
// SharedPreferences sharedPreferences= getSharedPreferences("test", Activity.MODE_PRIVATE);
//实例化SharedPreferences.Editor对象
// SharedPreferences.Editor editor = sharedPreferences.edit();
//用putString的方法保存数据
// editor.putBoolean("USER_ISLOGIN",true);
// editor.putString("USER_ID", object.toString());
// editor.putString("USER_PWD", "pwd123");
//提交当前数据
// editor.apply();
// Toast.makeText(getApplicationContext(),
// sp.getString("USER_NAME",object.toString())+ sp.getBoolean("AUTO_ISCHECK",true),
// Toast.LENGTH_LONG).show();
// 解析json数据
String jsonString=sp.getString("USER_NAME",object.toString());
JSONObject demoJson = null;
try {
demoJson = new JSONObject(jsonString);
// String name = demoJson.getString("phone");
int id=demoJson.getInt("id");
String flag = demoJson.getString("flag");
Toast.makeText(getApplicationContext(),
"flag:"+flag+",id:"+id,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
;
Intent intent = new Intent(LoginActivity.this, index.class);
startActivity(intent);
}else {
Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "登录失败!", Toast.LENGTH_LONG).show();
}
// if (Integer.parseInt(object.toString()) != 0) {
//
// SharedPreferences sharedPreferences= getSharedPreferences("test", Activity.MODE_PRIVATE);
// //实例化SharedPreferences.Editor对象
// SharedPreferences.Editor editor = sharedPreferences.edit();
// //用putString的方法保存数据
// editor.putBoolean("USER_ISLOGIN",true);
// editor.putString("USER_ID", "123456");
// editor.putString("USER_PWD", "pwd123");
// //提交当前数据
// editor.apply();
//
// Intent intent = new Intent(LoginActivity.this, index.class);
// startActivity(intent);
//// Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_LONG).show();
//
// } else {
// Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
// startActivity(intent);
// Toast.makeText(getApplicationContext(), "登录失败!", Toast.LENGTH_LONG).show();
// }
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
// return email.contains("@");
return email.length() == 11;
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Use an AsyncTask to fetch the user's email addresses on a background thread, and update
* the email text field with results on the main UI thread.
*/
class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... voids) {
ArrayList<String> emailAddressCollection = new ArrayList<>();
// Get all emails from the user's contacts and copy them to a list.
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null, null, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract
.CommonDataKinds.Email.DATA));
emailAddressCollection.add(email);
}
emailCur.close();
return emailAddressCollection;
}
@Override
protected void onPostExecute(List<String> emailAddressCollection) {
addEmailsToAutoComplete(emailAddressCollection);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}