BackGroundThreadDemo

Start New project As in Previous :named it BackGroundThreadDemo

Now in activity_main.xml:
  • Add TextView
  • Add Button
  • Spinner
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/textView" />

    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="New Button"        android:id="@+id/button"        android:layout_below="@+id/textView"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_marginTop="85dp" />

    <ProgressBar        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/progressBar"        android:layout_centerVertical="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" />

</RelativeLayout>


NOw Came to ActivityMain.java

package com.broadway.backgroundthreaddemo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity{
    private TextView textView;
    private Button btn;
    private ProgressBar progressbar;
   
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button)findViewById(R.id.button);
        textView=(TextView)findViewById(R.id.textView);

        progressbar=(ProgressBar)findViewById(R.id.progressBar);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
               new MyAsyneTask().execute(url);
            }
        });

    }

    private  class  MyAsyneTask extends AsyncTask<String,Void,Void> {

        @Override        protected Void doInBackground(String... params) {
            ServiceHandler sh=new ServiceHandler();
           sh.makeServiceCall(params[0],ServiceHandler.GET,null);
            return null;
        }

        @Override        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(View.VISIBLE);
            textView.setText("task started");

        }

        @Override        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            textView.setText("task completed");
            progressbar.setVisibility(View.GONE);
        }

        @Override        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

}

now  you need service handler
After Downloading service handler you should copy this to package (where MainActivity.java)located

 ServiceHandler.java(copy this service handler code if you trouble in downloading servicehandler)
package com.broadway.backgroundthreaddemo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {
 
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
 
    public ServiceHandler() {
 
    }
 
    /**     * Making service call     * @url - url to make request     * @method - http request method     * */    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }
 
    /**     * Making service call     * @url - url to make request     * @method - http request method     * @params - http request params     * */    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
             
            // Checking http request method type            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
 
                httpResponse = httpClient.execute(httpPost);
 
            } else if (method == GET) {
                // appending params to url                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);
 
                httpResponse = httpClient.execute(httpGet);
 
            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         
        return response;
 
    }
}



Now run this project
Share on Google Plus

About super super

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.