Android 부분
권한 설정
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.socket_android">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/Theme.Socket_android">
<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>
build.gradle
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.socket_android"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
MainActivity
package com.example.socket_android;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.connect_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connectServer();
}
});
}
void connectServer(){
EditText ipv4AddressView = findViewById(R.id.IPAddress);
String ipv4Address = ipv4AddressView.getText().toString();
EditText portNumberView = findViewById(R.id.portNumber);
String portNumber = portNumberView.getText().toString();
String postUrl = "http://" + "10.0.2.2" + ":" + 5000 + "/";
// String postUrl= "http://"+ipv4Address+":"+portNumber+"/";
String postBodyText="Hello";
MediaType mediaType = MediaType.parse("text/plain");
//MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
RequestBody postBody = RequestBody.create(mediaType, postBodyText);
postRequest(postUrl, postBody);
}
void postRequest(String postUrl, RequestBody postBody) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// Cancel the post on failure.
call.cancel();
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
responseText.setText("Failed to Connect to Server");
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
try {
responseText.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}
파이썬 Flask
import flask
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def handle_request():
return "Flask Server & Android are Working Successfully"
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
23.06.12 추가
Android에서 사진 전송
void connectServer(){
String portNumber = "5000";
String postUrl= "baseUrl";
mCurrentPhotoPath = image.getAbsolutePath(); // 이미지 주소
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
// Read BitMap by file path
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
RequestBody postBodyImage = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", "androidFlask.jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray))
.build();
postRequest(postUrl, postBodyImage);
}
void postRequest(String postUrl, RequestBody postBody) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
runOnUiThread(new Runnable() {
// Server Connect Fail
@Override
public void run() {
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
}
}
});
Flask
@app.route('/model', methods = ['GET', 'POST'])
def handle_request():
# Recive Img
imagefile = request.files['image']
filename = datetime.today().strftime("%Y%m%d%H%M%S") + '.jpg'
imagefile.save(filename)
...
return "result"
'안드로이드 > 잡다한 지식' 카테고리의 다른 글
안드로이드 스튜디오 EditText 밑줄 제거 (0) | 2021.03.02 |
---|---|
안드로이드 스튜디오 Recycler View 사용 (0) | 2021.02.18 |
안드로이드 스튜디오 intent로 bitmap 넘기기 (0) | 2021.01.30 |
안드로이드 스튜디오 내부 데이터베이스 연결하기 (0) | 2021.01.25 |
안드로이드 스튜디오 문자 받기, 문자 전송하기 (0) | 2020.12.29 |