안드로이드 개발 질문/답변
(글 수 45,052)
아래 예제 코드에서 조금 의아한게 있어서 질문을 남기게 되었습니다.
다름이 아니라 다이얼로그 부분인데..
mProgress = new ProgressDialog(getApplicationContext());
이부분에서 위와 같이 getApplicationContext()로 인자를 넘기면 오류가 나서 정상 동작이 되지 않습니다.
반면에 인자로 getApplicationContext대신 클래스명.this로 넘기면 정상동작을 하였습니다.
그 이유가 알고 싶습니다.ㅠㅠ
package com.example.threadlongtimeasynctask;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private int mValue;
private TextView mText;
private Button btn;
private ProgressDialog mProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AccumulateTask().execute(100);
}
class AccumulateTask extends AsyncTask<Integer, Integer, Integer>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mValue = 0;
mProgress = new ProgressDialog(getApplicationContext());
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setTitle("Updataing..");
mProgress.setMessage("Wait..");
mProgress.setCancelable(false);
mProgress.setProgress(0);
mProgress.setButton("Cancle", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
cancel(true);
}
});
mProgress.show();
}
@Override
protected Integer doInBackground(Integer... arg0) {
// TODO Auto-generated method stub
while(isCancelled() == false) {
mValue++;
if(mValue <= 100) {
publishProgress(mValue);
}else {
break;
}
try {Thread.sleep(50);} catch(Exception e) {}
}
return mValue;
}
@Override
protected void onProgressUpdate(Integer... arg0) {
// TODO Auto-generated method stub
mProgress.setProgress(arg0[0]);
mText.setText(Integer.toString(arg0[0]));
}
@Override
protected void onPostExecute(Integer arg0) {
// TODO Auto-generated method stub
mProgress.dismiss();
}
@Override
protected void onCancelled() { //cancle 메서드로 작업을 취소 하였을때 실행되는 메서드이다.
// TODO Auto-generated method stub
mProgress.dismiss();
}
}
}
안드로이드 어플리케이션은 액티비티 위에 어플리케이션이라는 클래스가 존재합니다.
(윈도우 쪽의 app 객체랑 비슷한..)
그 어플리케이션의 컨텍스트를 가져오는 api 가 getApplicationContext() 인거같아요.
그러므로 현재 activity의 컨텍스트랑은 좀 달라요.
이거 참고하세요.
Context context = getApplicationContext();
if(context == ((Context)this)) {
Log.i("context", "activity");
}
else if(context == ((Context)getApplication())) {
Log.i("context", "application");
}