StratoSphere Stream

1. 메니페스토에 인터넷


2. 


package location.techdown.com.simplevideoplayer;

import android.media.AudioManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import java.net.URL;

public class MainActivity extends AppCompatActivity {
Button play;
Button stop;
VideoView videoView;
SeekBar seekBar;
AudioManager maudioManager = null;
TextView textView;

String url = "http://techslides.com/demos/sample-videos/small.mp4";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

play = findViewById(R.id.play);
stop = findViewById(R.id.stop);
videoView = findViewById(R.id.videoView);
seekBar = findViewById(R.id.seekBar);
textView = findViewById(R.id.textView);

//음량값 받기
maudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int maxVol = maudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//최대치 값을 가져와서 seekBar Max로 하기
seekBar.setMax(maxVol);
textView.setText("음량최대값: "+ maxVol);


//Seekbar로 음량 변경
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textView.setText("변환값 "+ i);
//음악 음량 변경
maudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, AudioManager.FLAG_SHOW_UI);
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});

MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
//주소변경
videoView.setVideoURI(Uri.parse(url));
videoView.requestFocus();

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//플레이
videoView.start();
}
});

stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//멈춤
videoView.stopPlayback();
}
});

}
}


응용판으로 Seekbar을 이용해서 음량을 조절할 수 있게 했다.

Comment : 0

1. 메니페스트에 인터넷 권한 승인하기


2. 

package location.techdown.com.sampleaudioplayer;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button play;
Button stop;
Button replay;
TextView textView;

static final String bgm = "http://mini-files.thinkpool.com/files/mini/2004/09/14/%EC%BD%94%EC%9A%94%ED%83%9C-%EB%B6%88%EA%BD%83.mp3";
private MediaPlayer mediaPlayer;
private int playbackPosition = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

play = findViewById(R.id.button);
stop = findViewById(R.id.button2);
replay = findViewById(R.id.button3);
textView = findViewById(R.id.textView);

play.setOnClickListener(this);
stop.setOnClickListener(this);
replay.setOnClickListener(this);


}

@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button: //play
playAudio(bgm);
Toast.makeText(getApplicationContext(), "재생", Toast.LENGTH_LONG).show();
break;
case R.id.button2: //stop
if (mediaPlayer != null) {
//현재 위치 받기
playbackPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause(); //멈춤
Toast.makeText(getApplicationContext(), "일시중지", Toast.LENGTH_LONG).show();
textView.setText("현재위치 : "+playbackPosition);
}
break;
case R.id.button3: //replay
//재생이 있고 재생중이 맞다면 실행
if (mediaPlayer != null && mediaPlayer.isPlaying() == false) {
//재시작을 하면 시작후 seekTo로 중단되었던 포지션으로 이동
mediaPlayer.start(); //시작
mediaPlayer.seekTo(playbackPosition); // 타임 위치로 가기

}
break;

}
}

@Override
protected void onDestroy() {
super.onDestroy();
killAudio();
}

public void playAudio(String url) {
killAudio();
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(url); // 주소 받기
mediaPlayer.prepare(); // 준비
mediaPlayer.start(); //시작
} catch (IOException e) {
e.printStackTrace();
}

}

private void killAudio() {
if (mediaPlayer != null) {
//리소스 해제
mediaPlayer.release();
}
}
}


Comment : 0


컨트롤 알트 S를 눌러서 설정으로 간 다음

Google play Service를 활성화.



컨트롤 알트 쉬프트 에스를 눌러서

프로젝트 구조에서 app -> Dependencies -> +

play-service 로 검색하면 maps달린거 추가. 


메니페스트


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.acid.samplelocation">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>

<permission
android:name="com.example.acid.samplelocation.permission.MAPS.RECEIVE"
android:protectionLevel="signature" />

<uses-permission android:name="com.example.acid.samplelocation.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICE" />

<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<uses-library android:name="com.google.android.maps"/>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="API키를 넣으면 된다."/>

<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

구글 Api key는 구글에서 구하면 된다.


layout


<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS ON"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS OFF"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<Button
android:id="@+id/buttonMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="버튼" />
</LinearLayout>

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

</LinearLayout>


package com.example.acid.samplelocation;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity {

TextView textView;
Button button;
Button button2;
Button buttonMap;

SupportMapFragment mapFragment;
GoogleMap map;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView1);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);

//버튼 맵
buttonMap = findViewById(R.id.buttonMap);

//지도 객체 참조
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;

//최초 표시 부분
//없으면 지도가 회색으로 나온다.
// 서울역으로
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(37.555744, 126.970431)));
//지도 Zoom 정도
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

}
});

//지도 인식
MapsInitializer.initialize(this);

buttonMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMylocation();
}
});

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestMylocation();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopLocation();
Toast.makeText(getApplicationContext(), "GPS OFF", Toast.LENGTH_LONG).show();
}
});
}



//class가 아닌 pricate 값으로 하나 만든다. remove를 위해서
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
showCurrentLocation(latitude, longitude);
}

public void showCurrentLocation(Double getLatitude, Double getLongitude) {
LatLng latLng = new LatLng(getLatitude, getLongitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));

//마커로 좌표 찍기
MarkerOptions marker = new MarkerOptions();
//마커에 넣을 정보
//snippet은 subtitle같은 것이다
marker.position(latLng).title("My position").snippet("my position");
//마커를 지도에 표기
map.addMarker(marker).showInfoWindow();

//마커를 누르면 실행되는 것
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getApplicationContext(), "클릭했음", Toast.LENGTH_LONG).show();
return false;
}
});


}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
};

LocationManager locationManager = null;

//내 위치 요청
public void requestMylocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //LOCATION_SERVICE
Location location = null;
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //네트워크가 활성화 되어 있다면
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //마지막에 알려진 위치
}

String getLongitude = "LAST getLongitude : " + location.getLongitude();
String getLatitude = " LAST getLatitude : " + location.getLatitude();
Log.i("Location ", getLongitude + "" + getLatitude);

Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
textView.setText("latitude " + latitude);

Toast.makeText(getApplicationContext(), "GPS", Toast.LENGTH_LONG).show();

long minTime = 10000; // 10초
long minDistance = 0;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);


}


//GPS중단
public void stopLocation() {
locationManager.removeUpdates(locationListener);
}


}

주석으로 설명은 달아놓았는데, GPS받는 부분에서 구글 맵 부분이 추가된 형태이다. 



Comment : 0

package com.example.acid.samplelocation;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

TextView textView;
Button button;
Button button2;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView1);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startLocationService();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopLocation();
Toast.makeText(getApplicationContext(), "GPS OFF", Toast.LENGTH_LONG).show();
}
});
}

private LocationListener locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
textView.setText(latitude + " "+longitude);
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
};

LocationManager locationManager = null;

public void startLocationService() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //LOCATION_SERVICE
Location location = null;
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ //네트워크가 활성화 되어 있다면
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}else{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //마지막에 알려진 위치
}

String getLongitude = "LAST getLongitude : " + location.getLongitude();
String getLatitude = " LAST getLatitude : " + location.getLatitude();
Log.i("Location ", getLongitude + "" + getLatitude);

textView.setText(getLongitude + "" + getLatitude);
Toast.makeText(getApplicationContext(), "GPS", Toast.LENGTH_LONG).show();


long minTime = 10000; // 10초
long minDistance = 0;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);
}

public void stopLocation(){
locationManager.removeUpdates(locationListener);
}


}

GPS 받고 끊고 


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

메니페스트에 이거 넣어야 한다. 

Comment : 0

2018/10/09 - [프로그래밍/안드로이드] - [안드로이드] Url에 요청해서 Json 받아오기 (Get)

에서도 다루었지만 이번엔 여러가지 JSON요청방식, 그리고 class를 따로 분리하는 방법을 쓴다.

(XML은 안바뀌었다)


 - 메인 엑티비티

package com.example.acid.jsonpost;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {

Button
button;
TextView textView;
EditText editText;

Button buttonGet;
EditText editTextGet;

TextView textViewSet;

Button buttonTest;

String getEditText = "";
String resultData = "";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Result TextView
textView = findViewById(R.id.textView3);

//Post Json 요청
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

//Get Json 요청
buttonGet = findViewById(R.id.button2);
editTextGet = findViewById(R.id.editText2);

textViewSet = findViewById(R.id.textView);

buttonTest = findViewById(R.id.button3);

//setOnClick connect
button.setOnClickListener(this);
buttonTest.setOnClickListener(this);
buttonGet.setOnClickListener(this);
}

public class threadforce extends Thread{
@Override
public void run() {
super.run();
//http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=805
String address = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + getEditText;
String resultData = "";

try {
URL url =
new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//GET or Post 설정
httpCon.setRequestMethod("GET");
//커넥션 타임아웃 설정 (서버 접속시 연결시간)
httpCon.setConnectTimeout(10 * 1000);
//Read시 타임아웃 설정
httpCon.setReadTimeout(10 * 1000);
// User-Agent 설정
httpCon.setRequestProperty("User-Agent", "Mozilla/9.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");

/* // Request Header값 셋팅 setRequestProperty(String key, String value)
httpCon.setRequestProperty("NAME", "name");
httpCon.setRequestProperty("MDN", "mdn");
httpCon.setRequestProperty("APPID", "appid");
// 서버 Response Data를 xml 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/xml");
// 서버 Response Data를 JSON 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/json");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "text/html");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/xml");
// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/json");
// 컨트롤 캐쉬 설정
httpCon.setRequestProperty("Cache-Control", "no-cache");
// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)
httpCon.setRequestProperty("Content-Length", "length")*/

//여기서 연결한다
httpCon.connect();

//Response code 불러오기
int code = httpCon.getResponseCode();
Log.d("Response Code", code + "");

if (code == 200) { //정상처리 200

//InputStream으로 읽어들인다.
InputStream response = httpCon.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(response, "UTF-8");
//버퍼 리더로 변환
BufferedReader bf = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line)
;
}
resultData = sb.toString()
;

Log.d("Json", resultData);

response.close();
bf.close();


} else { // 에러
resultData = "None";
}

httpCon.disconnect()
;

} catch (MalformedURLException e) {
e.printStackTrace()
;
} catch (IOException e) {
e.printStackTrace()
;
}
Message message =
mHandler.obtainMessage(101, resultData);
mHandler.sendMessage(message);
}
}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.button: // Json 보내기
Toast.makeText(getApplicationContext(), "button1을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editText.getText().toString();
//JSON 형태로 보내기
Thread threadPost = new Thread(this);
threadPost.start();

break;

case R.id.button2: // Get 방식 Json 가져오기 (Thread를 클래스 생성한 방식) httpCon.connect();으로 연결하는 방식
Toast.makeText(getApplicationContext(), "button2을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
threadforce thread =
new threadforce();
thread.start();

} catch (Exception e) {
e.printStackTrace()
;
}

break;

case R.id.button3: // 연결 Class 분리 한 방식 => Class는 Thread가 아니다.
Toast.makeText(getApplicationContext(), "테스트버튼.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
Thread thread =
new Thread(new Runnable() {

@Override
public void run() {
//생성할때 param값 넣어줌
getHttpConnection getConnectionData = new getHttpConnection(getEditText);
String threadResult = getConnectionData.httpconnect();
//Handler는 Thread안에서 돌아야 한다.
Message message = mHandler.obtainMessage(102, threadResult);
mHandler.sendMessage(message);

}
})
;
thread.start();

} catch (Exception e) {
e.printStackTrace()
;
}
break;
} //Switch
}


@Override
public void run() {
String address =
"http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=";
URL url = null;
try {
url =
new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Cache-Control", "no-cache");
httpCon.setRequestProperty("Content-Type", "application/json");
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setDoOutput(true); //outputstream으로 받겠다
httpCon.setDoInput(true); //InputStream으로 받겠다

//JSON으로 만듬
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "paul rudd");
JSONArray jsonArray = new JSONArray();
jsonArray.put("I Love You Man");
jsonArray.put("Role Models");
jsonObject.put("movies", jsonArray );
String param = jsonObject.toString();

//방식1
// OutputStreamWriter osw = new OutputStreamWriter(httpCon.getOutputStream());
// osw.write(param);
// osw.flush();
// osw.close();

OutputStream os = httpCon.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
os.close();

int resultCode = httpCon.getResponseCode();
if (resultCode != 200) {

}
else {
InputStreamReader isr =
new InputStreamReader(httpCon.getInputStream(), "UTF-8");
BufferedReader bf = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line)
;
}

httpCon.disconnect()
;
Message msg = mHandler.obtainMessage(102, sb.toString());
mHandler.handleMessage(msg);


}
}
catch (Exception e) {
e.printStackTrace()
;
}
}

private final MyHandler mHandler = new MyHandler(this);

public static class MyHandler extends Handler {
private final WeakReference<MainActivity> weakReference;

public MyHandler(MainActivity mainActivity) {
weakReference = new WeakReference<MainActivity>(mainActivity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

MainActivity mainactivity = weakReference.get();

if (mainactivity != null) {
switch (msg.what) {

case 101:
String jsonString = (String) msg.
obj;
String result = "";
try {
//String to Json
JSONObject jsonObj = new JSONObject(jsonString);
result = jsonObj.getString("firstAccumamnt");
} catch (JSONException e) {
e.printStackTrace()
;
}
mainactivity.
textView.setText(result);

break;

case 102:
String jsonStringPost = (String) msg.
obj;
String resultPost = "";
try {
//String to Json
JSONObject jsonObj = new JSONObject(jsonStringPost);
result = jsonObj.getString("validate");
} catch (JSONException e) {
e.printStackTrace()
;
}
mainactivity.
textView.setText(jsonStringPost);

break;
}
}
}
}
}

getConnectionData.class

package com.example.acid.jsonpost;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class getHttpConnection {

private String getEditText;
private String resultData;

public getHttpConnection(String getEditText) {
this.getEditText = getEditText;

}

public String httpconnect(){
//http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=805
String address = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + getEditText;
String resultData = "";

try {
URL url = new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//GET or Post 설정
httpCon.setRequestMethod("GET");
//커넥션 타임아웃 설정 (서버 접속시 연결시간)
httpCon.setConnectTimeout(10 * 1000);
//Read시 타임아웃 설정
httpCon.setReadTimeout(10 * 1000);
// User-Agent 설정
httpCon.setRequestProperty("User-Agent", "Mozilla/9.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");

/* // Request Header값 셋팅 setRequestProperty(String key, String value)
httpCon.setRequestProperty("NAME", "name");
httpCon.setRequestProperty("MDN", "mdn");
httpCon.setRequestProperty("APPID", "appid");
// 서버 Response Data를 xml 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/xml");
// 서버 Response Data를 JSON 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/json");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "text/html");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/xml");
// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/json");
// 컨트롤 캐쉬 설정
httpCon.setRequestProperty("Cache-Control", "no-cache");
// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)
httpCon.setRequestProperty("Content-Length", "length")*/

//여기서 연결한다
httpCon.connect();

//Response code 불러오기
int code = httpCon.getResponseCode();
Log.d("Response Code", code + "");

if (code == 200) { //정상처리 200

//InputStream으로 읽어들인다.
InputStream response = httpCon.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(response, "UTF-8");
//버퍼 리더로 변환
BufferedReader bf = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
resultData = sb.toString();

Log.d("Json", resultData);

response.close();
bf.close();


} else { // 에러
resultData = "None";
}

httpCon.disconnect();


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultData;
}


}

이전과 달리 클래스를 분리한 것도 있고, outputstream으로 실행하는 방법

그리고 Thread를 새로 생성해서 돌리는 방법등 여러가지를 시도해 본 코드이다. 

최종적으로는 Handler를 스레드에 넣어야 실행이 된다. 


Comment : 0

1. 메니페스트에 인터넷 권한 


<uses-permission android:name="android.permission.INTERNET"/>


2. xml 만들기

<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="데이터 가져오기"
android:textAlignment="center" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="JSON" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="테스트" />

</LinearLayout>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="값을 넣으세요." />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Get방식 api 가져오기" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Get Json" />
</LinearLayout>

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="800" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="* 결과창"
android:textSize="18sp"
android:textStyle="bold" />

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView" />
</LinearLayout>
</LinearLayout>



3. 코드쓰기


package com.example.acid.jsonpost;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutput;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {

Button button;
TextView textView;
EditText editText;

Button buttonGet;
EditText editTextGet;

TextView textViewSet;

Button buttonTest;

String getEditText = "";
String resultData ="";



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Result TextView
textView = findViewById(R.id.textView3);

//Post Json 요청
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

//Get Json 요청
buttonGet = findViewById(R.id.button2);
editTextGet = findViewById(R.id.editText2);

textViewSet = findViewById(R.id.textView);

buttonTest = findViewById(R.id.button3);

//setOnClick connect
button.setOnClickListener(this);
buttonTest.setOnClickListener(this);
buttonGet.setOnClickListener(this);
}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.button: // Json 보내기
Toast.makeText(getApplicationContext(), "button1을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editText.getText().toString();
resultData = JsonPost(getEditText);

textView.setText(resultData);
break;

case R.id.button2: // Get방식 Json 가져오기
Toast.makeText(getApplicationContext(), "button2을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
Thread thread = new Thread(this);
thread.start();
} catch (Exception e) {
e.printStackTrace();
}


break;

case R.id.button3: //
Toast.makeText(getApplicationContext(), "테스트버튼.", Toast.LENGTH_LONG).show();

break;
} //Switch
}


public String JsonPost(String getEditText) {
return "";
}

@Override
public void run() {
//http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=805
String address = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + getEditText;
String resultData = "";

try {
URL url = new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//GET or Post 설정
httpCon.setRequestMethod("GET");
//커넥션 타임아웃 설정 (서버 접속시 연결시간)
httpCon.setConnectTimeout(10 * 1000);
//Read시 타임아웃 설정
httpCon.setReadTimeout(10 * 1000);
// User-Agent 설정
httpCon.setRequestProperty("User-Agent", "Mozilla/9.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");

/* // Request Header값 셋팅 setRequestProperty(String key, String value)
httpCon.setRequestProperty("NAME", "name");
httpCon.setRequestProperty("MDN", "mdn");
httpCon.setRequestProperty("APPID", "appid");
// 서버 Response Data를 xml 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/xml");
// 서버 Response Data를 JSON 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/json");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "text/html");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/xml");
// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/json");
// 컨트롤 캐쉬 설정
httpCon.setRequestProperty("Cache-Control", "no-cache");
// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)
httpCon.setRequestProperty("Content-Length", "length")*/

//여기서 연결한다
httpCon.connect();

//Response code 불러오기
int code = httpCon.getResponseCode();
Log.d("Response Code", code + "");

if (code == 200) { //정상처리 200

//InputStream으로 읽어들인다.
InputStream response = httpCon.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(response, "UTF-8");
//버퍼 리더로 변환
BufferedReader bf = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
resultData = sb.toString();

Log.d("Json", resultData);

response.close();
bf.close();


} else { // 에러
resultData = "None";
}

httpCon.disconnect();




} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = mHandler.obtainMessage(101, resultData);
mHandler.sendMessage(message);
}

private final MyHandler mHandler = new MyHandler(this);
public static class MyHandler extends Handler{
private final WeakReference<MainActivity> weakReference;

public MyHandler(MainActivity mainActivity) {
weakReference = new WeakReference<MainActivity>(mainActivity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

MainActivity mainactivity = weakReference.get();

if (mainactivity != null) {
switch (msg.what) {

case 101:
String jsonString = (String)msg.obj;
String result = "";
try {
//String to Json
JSONObject jsonObj = new JSONObject(jsonString);
result = jsonObj.getString("firstAccumamnt");
} catch (JSONException e) {
e.printStackTrace();
}
mainactivity.textView.setText(result);

break;
}
}
}
}
}


주의점

Thread로 구현을 해야 한다. Task하고 Thread가 있는데 Thread가 범용성이 있는거 같아서 그쪽 코드를 참조했다.

작업을 완료하면 Handler로 보내서 Handler에서 구분된 코드로 작업을 실행한다.





Comment : 0

0.. XML에 onClick..


이건 책에 나오니 생략


1. 그냥 넣기 


Button button1 = findViewById(R.id.button1);

//new까지 쓴후 Alt 스페이스를 눌러서 자동완성

button2.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                

            }

        });


이 방법은 버튼 한두개 있을때나 가능한 이야기다.


2. implements로 View.OnClickListener 받아서 하기 


MainActivity에서는 

button = findViewById(R.id.button);
button.setOnClickListener(this);


이렇게 해준다. this로 받고 이걸 implements로 가는 구조. 

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

빨간줄이 뜨는데 뭔가 override가 되지 않아서 그렇다.

저 줄에서 alt + insert를 누르면 



이런게 뜬다.




implement method가오른쪽

override...가 왼쪽이다.

저기서 onClick을 선택하면 된다.

implement가 더 빨리 보인다.

@Override
public void onClick(View v){

switch(v.getId()){
case R.id.button1: //전송
Toast.makeText(getApplicationContext(),"전송!", Toast.LENGTH_LONG).show();
edittext.setText(""); //비우기
break;
case R.id.button2: // 닫기
onDestroy();
break;

}

}


안에서 스위치 문으로 쓰는 형태. 


이게 쓰기 편하다. 


 

Comment : 0


edittext.addTextChangedListener(new TextWatcher() {

            @Override

            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


}


            @Override

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {


            }


            @Override

            public void afterTextChanged(Editable editable) {

     //텍스트가 바뀌고 난 후

     String dataString = edittext.getText().toString();

     int d = dataString.getBytes().length;

     textview.setText(d +"/80 바이트");

            }

        });


에디트 텍스트를 받을때는 addTextChangedListener을 쓴다. 

여기서는 텍스트를 받아서 바이트로 보여주는 소스

Comment : 0