https://developer.riotgames.com/apis
라이엇 개발자 사이트에서 api 가 상세히 적혀있다.
로그인해서 api-key를 받았다.
api-key는 매일 갱신해야 한다.
닉네임과 api_key를 사용해서 request url을 구성한다.
닉네임으로는 받아올 수 없으므로 encryptedSummonerId 를 통해 받아온다.
summoner-v4에서 accountId를 통해 받는다.
인터넷 접근을 위해 권한 받아오기
<uses-permission android:name="android.permission.INTERNET" />
riot api를 통해 정보를 가져왔을 때 보이는 레이아웃.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="350dp"
android:layout_height="130dp"
android:gravity="center"
android:background="@drawable/id_register_item"
android:id="@+id/id_register_item"
android:visibility="gone"
tools:showIn="@layout/activity_main"
>
<ImageView
android:id="@+id/user_icon"
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_weight="1"
android:src="@drawable/garen"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="5"
android:orientation="vertical"
android:textAlignment="gravity">
<TextView
android:id="@+id/user_nickname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="TextView"
android:textColor="#006D44" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/user_level"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="TextView"
android:textColor="#006D44" />
<TextView
android:id="@+id/user_tier"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:text="TextView"
android:textColor="#006D44" />
</LinearLayout>
<TextView
android:id="@+id/user_mbti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="TextView"
android:textColor="#006D44" />
<TextView
android:id="@+id/user_manner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="TextView"
android:textColor="#006D44" />
</LinearLayout>
</LinearLayout>
를 통해 메인 레이아웃에 첨부시킨다.
아이디 등록이 되지 않았을 때는 안보이므로 visibility를 gone으로 설정했다.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="@layout/id_register_item" />
<Button
android:id="@+id/plus_id_register"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/register_game_id"/>
</LinearLayout>
</LinearLayout>
api를 받아오는 작업은 인터넷에서 리소스를 받아오는 작업이므로 스레드를 상속받았다.
class Name_API_Thread extends Thread
public Name_API_Thread(String Summoners_name){
this.Summoners_name = Summoners_name;
}
public JSONObject get(String strUrl){
try{
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setRequestMethod("GET");
con.setDoOutput(false);
StringBuilder sb = new StringBuilder();
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
//url에서 버퍼 형태로 데이터를 받음
BufferedReader br = new BufferedReader(new InputStreamReader
(con.getInputStream(), "utf-8"));
String line = br.readLine();
while((line != null)){
sb.append(line).append("\n");
line = br.readLine();
}
br.close();
String result = sb.toString();
//JSON 형태로 변환 후 리턴
JSONObject jsonObj = new JSONObject(result);
return jsonObj;
}else{
Log.d("wrong response: ", con.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
인자로 url 을 받아서 JSONObject로 리턴하는 메서드이다.
summoner-v4 와 league-v4 의 url 주소가 서로 다르므로 따로 메서드를 만들었다.
@Override
public void run() {
String SummonerName = this.Summoners_name.replaceAll(" ", "%20");
String requestURL = "https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + SummonerName + "?api_key=" + TOKEN;
//API lol_api = new API();
JSONObject jsonObj = get(requestURL);
try {
if(jsonObj == null){ is_success = false; return; }
else{ is_success = true;}
Summoners_id = (String) jsonObj.get("id");
Summoners_level = (int) jsonObj.get("summonerLevel");
Summoners_icon = (int) jsonObj.get("profileIconId");
Summoners_bitmap = getImageFromUrl("https://ddragon.leagueoflegends.com/cdn/10.18.1/img/profileicon/"+getSummoners_info("icon")+".png");
getInfo();
} catch (JSONException e) {
e.printStackTrace();
}
}
메인 액티비티에서 start 명령을 했을 때 수행되는 메서드이다.
TOKEN은 api_key.
이로써 encryptedSummonerId 와 레벨, 아이콘 id를 받을 수 있다.
public void getInfo(){
String requestURL = "https://kr.api.riotgames.com/lol/league/v4/entries/by-summoner/"+Summoners_id+"?api_key="+TOKEN;
JSONObject jsonObj = get(requestURL);
try {
Summoners_tier = (String) jsonObj.get("tier");
Summoners_rank = (String) jsonObj.get("rank");
Summoners_win = (int) jsonObj.get("win");
Summoners_lose = (int) jsonObj.get("lose");
} catch (JSONException e) {
e.printStackTrace();
}
}
encryptedSummonerId를 통해 티어, 랭크, 승리-패배 수를 받을 수 있다.
final EditText et = new EditText(getApplicationContext());
//닉네임을 받는 dialog
final AlertDialog.Builder alt_blt = new AlertDialog.Builder(MainActivity.this, R.style.plus_id_register_dialog_style);
alt_blt.setTitle("아이디 생성")
.setMessage("닉네임을 적어주세요")
.setCancelable(false)
.setView(et)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {...});
AlertDialog dialog = alt_blt.create();
dialog.show();
dialog를 통해서 유저의 닉네임을 받아온다.
[in OnClickListener]
public void onClick(DialogInterface dialogInterface, int i) {
String value = et.getText().toString();
//롤 닉네임으로 사용자의 id, level 티어, 승패를 받아온다.
apiThread = new Name_API_Thread(value);
try {
apiThread.start();
apiThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//만약 아이디가 없는 아이디라면 Toast로 메시지 도시하고 중단.
if(apiThread.getSummoners_info("is_success") == "false"){
Toast.makeText(getApplicationContext(), "Wrong NickName!!", Toast.LENGTH_SHORT).show();
return;
}
TextView user_nickname = (TextView) findViewById(R.id.user_nickname);
TextView user_level = (TextView) findViewById(R.id.user_level);
TextView user_tier = (TextView) findViewById(R.id.user_tier);
TextView user_mbti = (TextView) findViewById(R.id.user_mbti);
TextView user_manner = (TextView) findViewById(R.id.user_manner);
LinearLayout user_layout = (LinearLayout) findViewById(R.id.id_register_item);
plus_id_register.setVisibility(View.GONE);
user_layout.setVisibility(View.VISIBLE);
user_nickname.setText(value);
user_level.setText("Level: " + apiThread.getSummoners_info("level"));
user_tier.setText("Tier: " + apiThread.getSummoners_info("tier"));
user_mbti.setText("MBTI: INFT");
user_manner.setText("Manner: "+"SUCK");
ImageView user_icon = (ImageView) findViewById(R.id.user_icon);
user_icon.setImageBitmap(apiThread.getSummoners_bitmap());
}
apiThread.join();
: 정보를 받아오기 전에 빈 값으로 액티비티의 뷰 내용을 채우는 문제 때문에 해당 쓰레드가 종료되기까지 기다렸다가 넘어가게
Summoners_icon 에 우리가 가져와야할 유저의 아이콘의 인덱스가 저장되어 있다. 이를 이용해서 url을 이용해 비트맵을 받아왔다.
url: "https://ddragon.leagueoflegends.com/cdn/10.18.1/img/profileicon/" + Summoners_icon + ".png"
public Bitmap getImageFromUrl(String urlStr){
Bitmap imgBitmap = null;
try{
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.connect();
BufferedInputStream bf = new BufferedInputStream(con.getInputStream());
imgBitmap = BitmapFactory.decodeStream(bf);
bf.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgBitmap;
}
public Bitmap getSummoners_bitmap(){
return Summoners_bitmap;
}
부족한 코드 봐주셔서 감사드립니다. 구글링하면서 코드들 많이 섞었는데 쉽지 않네요.
피드백 환영합니다.