Newer
Older
CosmosClient / app / src / main / java / com / example / cosmosclient / views / SigninActivity.java
package com.example.cosmosclient.views;

import android.content.Context;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.cosmosclient.R;
import com.example.cosmosclient.app.Cosmos;
import com.example.cosmosclient.entities.SigninResponse;
import com.example.cosmosclient.resources.UsersRest;
import com.example.cosmosclient.services.CosmosBackgroundService;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class SigninActivity extends AppCompatActivity {
    private boolean uIdEnable;
    private boolean pwEnable;
    private Button SigninButton;
    private Intent intentservice;
    private static final int REQUEST_MULTI_PERMISSIONS = 101;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        Context context = getApplicationContext();

        // Android 6, API 23以上でパーミッシンの確認
        if(Build.VERSION.SDK_INT >= 23){
            checkMultiPermissions();
        }
        else{
            startService();
        }

        //各種IDを取得
        SigninButton = findViewById(R.id.SigninButton);
        Button SignupButton = findViewById(R.id.SignupButton);
        final EditText UserIdText = findViewById(R.id.UserIdText);
        final EditText PasswordText = findViewById(R.id.PasswordText);
        Button ForgotPasswordButton = findViewById(R.id.ForgotPasswordButton);

        Cosmos app = (Cosmos) getApplication();
        String account  = app.getuId();

        // 空チェック
        if (account != null && account.length() > 0) {
            // 保存済の情報をログインID欄に設定
            UserIdText.setText(account);
            uIdEnable=true;
            //UserIdText.setEnabled(false);
        }

        //ボタン無効化
        SigninButton.setEnabled(false);

        //TextWatcherで入力監視
        UserIdText.addTextChangedListener(new SigninActivity.GenericTextWatcher(UserIdText));
        PasswordText.addTextChangedListener(new SigninActivity.GenericTextWatcher(PasswordText));


        //retrofitの処理
        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/cosmos/rest/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        //interfaceから実装を取得
        final UsersRest signinService = retrofit.create(UsersRest.class);

        //Sign inボタンの処理
        SigninButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //ボタン連打防止
                SigninButton.setEnabled(false);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        SigninButton.setEnabled(true);
                    }
                }, 1000L);

                //APIに値を送信
                Call<SigninResponse> call = signinService.login(UserIdText.getText().toString(), PasswordText.getText().toString());

                //サーバからのレスポンス
                call.enqueue(new Callback<SigninResponse>() {
                    //成功時
                    @Override
                    public void onResponse(Call<SigninResponse> call, Response<SigninResponse> response) {
                        if (response.isSuccessful()) {
                            if(response.body() == null){
                                //パスワードが違う際、アプリが落ちてしまうため
                                Toast.makeText(SigninActivity.this,
                                        "パスワードが違います",Toast.LENGTH_LONG).show();
                            }else{
                                SigninResponse result = response.body();

                                //app/Cosmosに情報保存
                                Cosmos app = (Cosmos) getApplication();
                                app.setToken(result.token);
                                app.setuId(UserIdText.getText().toString());

                                //画面遷移
                                Intent intent = new Intent(getApplication(), GroupListActivity.class);
                                startActivity(intent);
                                Toast.makeText(SigninActivity.this,
                                        "ログインしました", Toast.LENGTH_SHORT).show();
                                finish();
                            }

                        }else{
                            //onFailureでキャッチできないエラーの処理
                            Toast.makeText(SigninActivity.this,
                                    "通信エラー",Toast.LENGTH_SHORT).show();
                        }
                    }

                    //失敗時
                    @Override
                    public void onFailure(Call<SigninResponse> call, Throwable t) {
                        t.printStackTrace();
                        Toast.makeText(SigninActivity.this,
                                "ユーザIDもしくはパスワードが間違っています",Toast.LENGTH_SHORT).show();
                    }

                });
            }
        });

        //サインアップ画面への遷移処理
        SignupButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent intent = new Intent(getApplication(), SignupActivity.class);
                startActivity(intent);
                finish();
            }
        });

        //パスワード再登録画面への遷移処理
        ForgotPasswordButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent intent = new Intent(getApplication(), ForgotPasswordActivity.class);
                startActivity(intent);
                //finish();
            }
        });
    }


    private class GenericTextWatcher implements TextWatcher{
        private View view;

        private GenericTextWatcher(View view){
            this.view = view;
        }

        @Override
        public  void beforeTextChanged(CharSequence s, int start, int count,int after){
            /*記述不要*/
        };
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count){/*記述不要*/};

        @Override
        public void afterTextChanged(Editable s){
            switch(view.getId()) {
                case R.id.UserIdText:
                    if (s.length()>0) {
                        uIdEnable = true;
                    } else {
                        uIdEnable = false;
                    }
                    break;
                case R.id.PasswordText:
                    if(s.length()>0){
                        pwEnable=true;
                    }else{
                        pwEnable=false;
                    }
                    break;
            }
            //ボタン有効&無効
            if(uIdEnable && pwEnable){
                SigninButton.setEnabled(true);
            }else{
                SigninButton.setEnabled(false);
            }
        }
    }
    // 結果の受け取り
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == REQUEST_MULTI_PERMISSIONS) {
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++) {
                    // 位置情報
                    if (permissions[i].
                            equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            // 許可された

                        } else {
                            // それでも拒否された時の対応
                            toastMake("位置情報の許可がないので計測できません");
                        }
                    }
                    // 外部ストレージ
                    else if (permissions[i].
                            equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            // 許可された
                        } else {
                            // それでも拒否された時の対応
                            toastMake("外部書込の許可がないので書き込みできません");
                        }
                    }
                }

                startService();

            }
        }
        else{
            //
        }
    }
    // 位置情報許可の確認、外部ストレージのPermissionにも対応できるようにしておく
    private  void checkMultiPermissions(){
        // 位置情報の Permission
        int permissionLocation = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        // 外部ストレージ書き込みの Permission
        int permissionExtStorage = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        ArrayList reqPermissions = new ArrayList<>();

        // 位置情報の Permission が許可されているか確認
        if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
            // 許可済
        }
        else{
            // 未許可
            reqPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }


        // 未許可
        if (!reqPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    (String[]) reqPermissions.toArray(new String[0]),
                    REQUEST_MULTI_PERMISSIONS);
            // 未許可あり
        }
        else{
            // 許可済
            startService();
        }
    }
    //serviceをスタートさせる
    private void startService() {
        Thread thread = new Thread() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            public void run() {
                intentservice = new Intent(SigninActivity.this, CosmosBackgroundService.class);
                startForegroundService(intentservice);

            }
        };
        thread.start();
    }
    // トーストの生成
    private void toastMake(String message){
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
        // 位置調整
        toast.setGravity(Gravity.CENTER, 0, 200);
        toast.show();
    }
}