본문 바로가기

안드로이드 Android

[모바일프로그래밍] 10-3 Intent service class

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="141dp"
        android:layout_marginTop="74dp"
        android:layout_marginEnd="174dp"
        android:text="Intent Service 실습"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="96dp"
        android:layout_marginTop="76dp"
        android:text="Download from internet"
        android:onClick="onClicked"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

DownloadService.java

package com.example.myapplication;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.renderscript.ScriptGroup;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class DownloadService extends IntentService {
    private int result = Activity.RESULT_CANCELED;

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    protected void onHandleIntent(Intent myintent) {
        Uri data = myintent.getData();
        String urlpath = myintent.getStringExtra("uripath");
        String buffer = " ";

        InputStream instream = null;

        try {
            URL url = new URL(urlpath);
            instream = url.openConnection().getInputStream();
            InputStreamReader reader = new InputStreamReader(instream);
            int i = 0, next = -1;
            while ((next = reader.read()) != -1) {
                buffer += " " + (char) next;
                if (++i > 100) break;
            }
            result = Activity.RESULT_OK;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (instream != null) {
                try {
                    instream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        Bundle extras = myintent.getExtras();
        if (extras != null) {
            Messenger messenger = (Messenger) extras.get("MESSENGER");
            Message msg = Message.obtain();
            msg.arg1 = result;
            msg.obj = buffer;
            try {
                messenger.send(msg);
            } catch (android.os.RemoteException e1) {
                Log.w(getClass().getName(), "Exception sending message", e1);
            }
        }
    }
}

MainActivity.java

package com.example.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private Handler myhandler = new Handler() {
        public void handleMessage(Message message) {
            Object path = message.obj;
            if (message.arg1 == RESULT_OK && path != null) {
                Toast.makeText(getApplicationContext(), " " + path.toString() + " 다운로드 완료", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "다운로드 실패함", Toast.LENGTH_LONG).show();
            }
        }
    };

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

    public void onClicked(View v) {
        Intent myinent = new Intent(this, DownloadService.class);
        Messenger messenger = new Messenger(myhandler);
        myinent.putExtra("MESSENGER", messenger);
        myinent.setData(Uri.parse("http://www.daum.net"));
        myinent.putExtra("urlpath", "http://www.daum.net");
        startService(myinent);
    }
}

AVD에는 인터넷이 연결되어 있지 않아서 테스트 할 수 없다.