본 내용은 강의 수강 내용과 인터넷 검색해서 보강한 자료를 기록해둔다.
AsyncTask 는 Thread 보다 자주 사용하며, MySQL(PHP) 서버와의 통신에서도 사용한다.
import 추가는 Alt + Enter 를 누르라고 팝업 알림창이 나온다. 그러면 눌러주면 된다.
Android Studio 는 오프라인 강의를 들었는데, 단축키 기능이 너무 편리하다.
XML 코드 작성시에도 기본적인 것부터 작성할 수 있게 하고 명령어를 일부 넣어주면 자동으로 팝업되면서 자동완성 기능을 편하게 완성시킨다.
package com.tistory.link2me.app10;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn_alert;
Button btn_custom;
Button btn_progress;
TextView txt;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_alert = (Button) findViewById(R.id.btn01);
btn_custom = (Button) findViewById(R.id.btn02);
btn_progress = (Button) findViewById(R.id.btn03);
txt = (TextView) findViewById(R.id.tv01);
btn_alert.setOnClickListener(listener);
btn_custom.setOnClickListener(listener);
btn_progress.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn01:
new AlertDialog.Builder(MainActivity.this)
.setTitle("2017 프로야구 우승후보")
.setMessage("두산 베어스")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
txt.setText("두산 베어즈");
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "NO", Toast.LENGTH_LONG).show();
txt.setText("LG 트윈스");
}
})
.show();
break;
case R.id.btn02:
LinearLayout linearLayout = (LinearLayout) View.inflate(MainActivity.this, R.layout.custom, null);
final EditText editText = (EditText) linearLayout.findViewById(R.id.et01);
new AlertDialog.Builder(MainActivity.this)
.setTitle("2017 프로야구 우승 후보")
.setView(linearLayout)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
String winner = editText.getText().toString();
txt.setText(winner);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
})
.show();
break;
case R.id.btn03:
DownloadTask task = new DownloadTask(MainActivity.this);
task.execute(100);
break;
}
}
};
private class DownloadTask extends AsyncTask<Integer, String, Integer> {
ProgressDialog progressDialog;
private Context mContext;
public DownloadTask(Context context){
mContext =context;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIcon(android.R.drawable.ic_dialog_info);
progressDialog.setTitle("Download");
progressDialog.setMessage("다운로드 중...");
progressDialog.show(); // show dialog
super.onPreExecute();
}
@Override
protected Integer doInBackground(Integer... params) {
//doInBackground 함수는 excute() 실행시 실행됨
final int taskCnt = params[0]; // 최대 몇인지 설정하는 변수
publishProgress("max", Integer.toString(taskCnt));
try {
for (int i = 0; i < taskCnt; i++) {
publishProgress("progress", Integer.toString(i), "번호 " + Integer.toString(i) + "번 수행중");
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return taskCnt; // onPostExecute()함수의 인수가 됨
}
@Override
protected void onProgressUpdate(String... progress) {
//onProgressUpdate() 함수는 publishProgress() 함수로 넘겨준 데이터들을 받아옴
if (progress[0].equals("progress")) {
progressDialog.setProgress(Integer.parseInt(progress[1]));
progressDialog.setMessage(progress[2]);
}
else if (progress[0].equals("max")) {
progressDialog.setMax(Integer.parseInt(progress[1]));
}
}
@Override
protected void onPostExecute(Integer result) {
//onPostExecute() 함수는 doInBackground() 함수가 종료되면 실행됨
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
첨부한 파일은 Android Studio 에서 프로젝트 생성하고 첨부한 파일을 참조해서 작성하면 도움이 된다.
'안드로이드 > Android Data 통신' 카테고리의 다른 글
안드로이드 AsyncTask.execute(new Runnable() (0) | 2017.04.16 |
---|---|
Android Studio 로그인 처리 (2) | 2017.03.30 |
안드로이드와 PHP 로그인 연동처리 (자동로그인, 세션처리, 네트워크 상태 체크 포함) (2) | 2016.07.07 |
안드로이드 PHP 연동 JSON 방식 검색기능 추가 (POST 방식) (0) | 2016.07.01 |
안드로이드 PHP 연동 JSON 방식 검색기능 추가 (GET 방식) (0) | 2016.07.01 |
보통 deprecate 되어도 이전 코드를 지우는 건 아니기 때문에, 전처럼 동작하기는 할 것이다.
향후, 유지보수단계에서 deprecate 코드에 대해서 안정성을 보장하지 않는다는 얘기이기 때문에, 안드로이드 차기 버전 에서는 비정상 동작을 할 가능성이 높아진다.
대체코드를 찾아서 새롭게 구현하는게 현명한 판단이다.
메모리 누수를 일으키는 현상에 대한 정리가 잘된 자료이다.
http://sjava.net/2016/05/%EB%B2%88%EC%97%AD-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%EC%95%B1%EC%9D%B4-%EB%A9%94%EB%AA%A8%EB%A6%AC-%EB%88%84%EC%88%98leak%EB%A5%BC-%EB%A7%8C%EB%93%9C%EB%8A%94-8%EA%B0%80%EC%A7%80/
depricated 로 나온 걸 하나 하나 해결하기 위해 찾은 걸 적어나갈 것이다.
URLDecoder.decode(getIntent().getExtras().getString("url"), "UTF-8");
getSettings().setUserAgent(0); => getSettings().setUserAgentString("Android");
URLEncoder.encode("","UTF-8")
Implicitly using the default locale is a common source of bugs: Use toUpperCase(Locale) instead NetworkCheck.java
url = url.toLowerCase(); ==> url = url.toLowerCase(Locale.getDefault());
// http://beginnersbook.com/2013/12/java-string-tolowercase-method-example/
The method decode(String) from the type URLDecoder is deprecated
URLEncoder.encode(String s, String enc);
import java.net.URLEncoder;
URLEncoder.encode("This text must be encoded!", "UTF-8");
AlertDialog: BUTTON_POSITIVE, BUTTON_NEUTRAL and BUTTON_NEGATIVE.
AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(" [ 알림 ]");
alertDialog.setMessage("등록된 휴대폰 번호가 없습니다.");
alertDialog.setButton("확인", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
alertDialog.setTitle(" [ 알림 ]")
.setMessage("등록된 휴대폰 번호가 없습니다.")
.setCancelable(false)
.setNegativeButton("확인",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialog.create();
alert.show();
alertDialog.setButton("확인", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"확인", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// http://www.technotalkative.com/issue-using-setjavascriptenabled-can-introduce-xss-vulnerabilities-application-review-carefully/
@SuppressLint("SetJavaScriptEnabled")
public class MyActivity extends Activity
{
...
}
// 내용 파악이 필요한 부분
showDialog(DIALOG_DOWNLOAD_PROGRESS);
The method showDialog(int) from the type Activity is deprecated
https://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29
This method was deprecated in API level 13.
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));