Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.hassansbeity.testingsevices;
- import android.app.IntentService;
- import android.content.Intent;
- import android.support.annotation.Nullable;
- import android.util.Log;
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- /**
- * Created by hassansbeity on 4/23/17.
- * Service_HTTP_URL: Retrieve an HTML page from the internet and store it locally
- */
- public class Service_HTTP_URL extends IntentService{
- public static final String CONSTANT_COM="com.Sbeyti.URL";
- public Service_HTTP_URL(){super("'HTTP_URL");}
- @Override
- protected void onHandleIntent(@Nullable Intent intent) {
- Log.v("ServiceStatus","Service Started");
- final String message= intent.getStringExtra("data");
- Thread thread = new Thread(new Runnable() {
- public void run() {
- // do the work that the service needs to do
- doInBackground();
- Intent backIntent= new Intent();
- backIntent.putExtra("data",message+" Back from Service");
- backIntent.setAction(CONSTANT_COM);
- sendBroadcast(backIntent);
- }
- });
- thread.start();
- }
- public void doInBackground() {
- URL url;
- HttpURLConnection urlConnection = null;
- File myFile=null;
- PrintWriter pr=null;
- try {
- url = new URL("http://www.android.com/");
- Log.v("ServiceStatus","Trying to Connect");
- urlConnection = (HttpURLConnection) url.openConnection();
- Log.v("ServiceStatus","Connected");
- InputStream in = urlConnection.getInputStream();
- InputStreamReader isw = new InputStreamReader(in);
- try {
- myFile = new File(getFilesDir()+"/dataRecieved.txt");
- pr = new PrintWriter(myFile);
- }catch(IOException e){
- Log.v("ServiceStatus",e.getMessage());
- }
- int data = isw.read();
- Log.v("ServiceStatus","downloading");
- while (data != -1) {
- char current = (char) data;
- data = isw.read();
- pr.print(current);
- }
- } catch (Exception e) {
- Log.v("ServiceStatus",e.getMessage());
- } finally {
- if (urlConnection != null) {
- urlConnection.disconnect();
- pr.close();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement