안드로이드(Android) 서비스의 쓰레드(Thread)에서 HttpUrlConnection을 이용하여 웹페이지 긁어오기

FSP 0 747 03.09 19:56

안드로이드(Android) 서비스의 쓰레드(Thread)에서 HttpUrlConnection을 이용하여 웹페이지 긁어오기 


8. Android 서비스의 쓰레드(Thread)에서 HttpUrlConnection을 이용하여 웹페이지 긁어오기

 

b49c474413e5ee73d266a4fd6ee8c430_1489056



1. 안드로이드에서 HttpServiceApplication 프로젝트 생성, 도메인명은 topcredu.co.kr, 다음 화면에서 NEXT 클릭 후 Empty Activity 선탯 후 MainActivity 그대로 둔 채로 Finish

 

2. [activity_main.xml]

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
   
tools:context="kr.co.topcredu.httpserviceapplication.MainActivity">

    <
LinearLayout
       
android:orientation="vertical"
       
android:layout_width="368dp"
       
android:layout_height="495dp"
        
android:layout_centerHorizontal="true"
       
tools:layout_editor_absoluteY="8dp"
       
tools:layout_editor_absoluteX="8dp">

        <
Button
           
android:text="CALL HTTP Service"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:id="@+id/btnStart"
           
style="@style/Widget.AppCompat.Button.Colored"
           
android:elevation="0dp" />

        <
Button
           
android:text="Stop HTTP Service"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:id="@+id/btnStop"
           
style="@style/Widget.AppCompat.Button.Colored" />

        <
Button
           
android:text="Print HTTP Result"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:id="@+id/btnPrint"
           
style="@style/Widget.AppCompat.Button.Colored" />

        <
TextView
           
android:id="@+id/textView"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:text="Display HTTP Result "
           
android:scrollbars="vertical"
           
tools:maxLines="@android:integer/status_bar_notification_info_maxnum" />

    </
LinearLayout>

</
android.support.constraint.ConstraintLayout>

 

3. 안드로이드 서비스 작성

 

[HttpService.java]

 

package kr.co.topcredu.httpserviceapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpService extends Service {
   
private static String LOG_TAG = "Http Service";
   
final StringBuilder output = new StringBuilder("Hello");
    IBinder
iBinder = new MyBinder();

   
//아래 Binder iBinder인터페이스 구현체이다.
   
class MyBinder extends Binder {
        HttpService getService() {
           
return HttpService.this; //서비스객체리턴
       
}
    }
   
@Nullable
    @Override
   
public IBinder onBind(Intent intent) {
        Log.i(
LOG_TAG, "Http Service onBind...");
       
return iBinder;
    }

   
@Override
   
public void onCreate() {
       
super.onCreate();
        Log.i(
LOG_TAG, "Http Service onCreate...");

       
//Thread를 이용하여 서비스 생성
        //
길게 수행되는 서비스인 경우 분리된 쓰레드를 이용할 것
       
new Thread(new Runnable() {
           
@Override
           
public void run() {
               
try {
                    URL url =
new URL("http://ojc.asia/");
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                   
if (conn != null) {
                        Log.i(
LOG_TAG, "Thread run 메소드..." + conn.toString());
                        conn.setConnectTimeout(
5000);
                        conn.setRequestMethod(
"GET");
                        conn.setDoInput(
true);
                        conn.setDoOutput(
true);

                       
int resCode = conn.getResponseCode();
                        Log.i(
LOG_TAG, "Thread run 메소드...응덥코드 :::: " + String.valueOf(resCode));
                       
if (resCode == HttpURLConnection.HTTP_OK) {
                            Log.i(
LOG_TAG, "Thread run 메소드 HTTP OK..." + conn.toString());
                            BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream())) ;
                            String line =
null;
                           
while(true) {
                                line = reader.readLine();
                               
if (line == null) {
                                   
break;
                                }
                               
output.append(line + "\n");
                            }

                            reader.close();
                            conn.disconnect();
                        }
                    }
                }
catch(Exception ex) {
                    Log.e(
"Http Service", "Exception in processing response.", ex);
                    ex.printStackTrace();
                }
               
//stopSelf(); //태스크가 끝나면 서비스 종료
           
}
        }).start();
        Log.i(
LOG_TAG, "Thread Start OK...===> " + output.toString());
    }

   
@Override
   
public void onRebind(Intent intent) {
       
super.onRebind(intent);
        Log.i(
LOG_TAG, "Http Service onRebind...");
    }

   
@Override
   
public boolean onUnbind(Intent intent) {
        Log.i(
LOG_TAG, "Http Service onUnbind...");
       
return super.onUnbind(intent);
    }

   
@Override
   
public void onDestroy() {
       
super.onDestroy();
        Log.i(
LOG_TAG, "Http Service onDestroy...");
    }

   
public String getResult() {
       
return output.toString();
    }
}

 

 

4. 메인 액티비티

 

[MainActivity.java]

 

package kr.co.topcredu.httpserviceapplication;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

   
private static String LOG_TAG = "MainActivity";

    Button
btnStart, btnStop, btnPrint;
    TextView
textView;

   
//BoundService에서 이용, MainActivity MyBoundService에 바인딩된지 여부
   
boolean isBoundService = false;
    HttpService
mService;

   
private ServiceConnection mServiceConnection = new ServiceConnection() {
       
@Override
       
public void onServiceConnected(ComponentName name, IBinder service) {
            HttpService.MyBinder myBinder = (HttpService.MyBinder) service;
           
mService = myBinder.getService();
           
isBoundService = true;
        }

       
@Override
       
public void onServiceDisconnected(ComponentName name) {
           
isBoundService = false;
        }
    };

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

       
textView = (TextView) findViewById(R.id.textView);
       
//텍스트뷰 스크롤바 추가
       
textView.setMovementMethod(new ScrollingMovementMethod());

       
// Bound Service, bindService() 이용
       
btnStart = (Button) findViewById(R.id.btnStart);
        
btnStop = (Button) findViewById(R.id.btnStop);
       
btnPrint = (Button)findViewById(R.id.btnPrint);

       
//Bound Service, bindService
       
btnStart.setOnClickListener(this);
       
btnStop.setOnClickListener(this);
       
btnPrint.setOnClickListener(this);
    }

   
@Override
   
protected void onStop() {
       
super.onStop();
       
if (isBoundService) {
            unbindService(
mServiceConnection);
           
isBoundService = false;
        }
    }

   
@Override
   
public void onClick(View v) {
       
switch(v.getId()) {
           
//Bound Service, bindService 이용
           
case R.id.btnStart :
                Intent intent =
new Intent(this, HttpService.class);
                startService(intent);
                bindService(intent,
mServiceConnection, Context.BIND_AUTO_CREATE);
                Log.i(
LOG_TAG, "Http Service Start...");
               
isBoundService = true;
               
break;
           
case R.id.btnStop :
               
if (isBoundService) {
                    unbindService(
mServiceConnection);
                   
isBoundService = false;
                    Log.i(
LOG_TAG, "Http Service Stop...");
                }
               
break;
           
case R.id.btnPrint :
               
if (isBoundService) {
                   
textView.setText(mService.getResult());
                    Log.i(
LOG_TAG, mService.getResult());
                }
               
break;
        }
    }
}

 

 

5. AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="kr.co.topcredu.httpserviceapplication">
 

<!—네트워크 권한 설정 à
    <
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <
uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <
uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <
uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

    <
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">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <
service android:name=".HttpService" android:enabled="true"/>  <!—서비스 à
    </
application>

</
manifest>

 

 

 

 

 

 

Comments