2016年12月24日土曜日

Android IntentService 类

Android IntentService 类

https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件


//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.e560.m1217a">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".MyServer"></service>
    </application>
</manifest>


//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    private int i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout linearLayout = new LinearLayout(this);
        Button bt = new Button(this);
        bt.setText("SaveFiletoAndroidFile");
        linearLayout.addView(bt);
        setContentView(linearLayout);
        i = 0;
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i++;
                SavetoServer(i);
            }
        });
    }

    protected void SavetoServer(int i) {
        String[] imgURLs = new String[]{
                "https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
                "https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
                "https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
                "https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
                "https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
        };
        Intent intent = new Intent(this, MyServer.class);
        intent.putExtra("URL", imgURLs[i].toString());
        startService(intent);
    }
}

//////////////////////////////////////////////////////////////////////
import android.app.IntentService;
import android.content.Intent;

public class MyServer extends IntentService {

    public MyServer() {
        super("test");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        HTTPClient httpClient = new HTTPClient(getApplicationContext(), intent.getStringExtra("URL"));
    }
}

//////////////////////////////////////////////////////////////////////
import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HTTPClient {
    private String urlString;
    private String FileName;
    private String savePath;
    private Context context;


    public HTTPClient(Context context, String urlString) {
        this.context = context;
        this.urlString = urlString.replace("\\", "");
        this.savePath = String.valueOf(this.context.getFilesDir());
        FileName = getFname(urlString);
        System.out.println("Thread.name Httpclient" + Thread.currentThread().getName());
        SaveFile();
    }

    public void SaveFile() {
        try {
            URL url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5 * 1000);
            httpURLConnection.setReadTimeout(5 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            if (httpURLConnection.getResponseCode() == 200) {
                File SaveF = new File(this.savePath + "/" + this.FileName);
                InputStream inputStream = httpURLConnection.getInputStream();
                FileOutputStream fos = new FileOutputStream(SaveF);
                byte[] buff = new byte[4096];
                int len = 0;
                while ((len = inputStream.read(buff)) != -1) {
                    fos.write(buff, 0, len);
                    fos.flush();
                }
                fos.close();
                inputStream.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected String getFname(String url) {
        String[] temp = url.split("/");
        return temp[temp.length - 1];
    }
}








0 件のコメント: