URL Network Connection – Android Java Example


Here is the content of src/MainActivity.java.

package com.tutorialspoint.myapplication;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends ActionBarActivity {
   private ProgressDialog progressDialog;
   private Bitmap bitmap = null;
   Button b1;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      b1 = (Button) findViewById(R.id.button);
      
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            checkInternetConenction();
            downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
         }
      });
   }
   
   private void downloadImage(String urlStr) {
      progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
      final String url = urlStr;
      
      new Thread() {
         public void run() {
            InputStream in = null;
            
            Message msg = Message.obtain();
            msg.what = 1;
            
            try {
               in = openHttpConnection(url);
               bitmap = BitmapFactory.decodeStream(in);
               Bundle b = new Bundle();
               b.putParcelable("bitmap", bitmap);
               msg.setData(b);
               in.close();
            }
            
            catch (IOException e1) {
               e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);
         }
      }.start();
   }
   
   private InputStream openHttpConnection(String urlStr) {
      InputStream in = null;
      int resCode = -1;
      
      try {
         URL url = new URL(urlStr);
         URLConnection urlConn = url.openConnection();
         
         if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException("URL is not an Http URL");
         }
         HttpURLConnection httpConn = (HttpURLConnection) urlConn;
         httpConn.setAllowUserInteraction(false);
         httpConn.setInstanceFollowRedirects(true);
         httpConn.setRequestMethod("GET");
         httpConn.connect();
         resCode = httpConn.getResponseCode();
         
         if (resCode == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
         }
      }
      
      catch (MalformedURLException e) {
         e.printStackTrace();
      }
      
      catch (IOException e) {
         e.printStackTrace();
      }
      return in;
   }
   
   private Handler messageHandler = new Handler() {
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         ImageView img = (ImageView) findViewById(R.id.imageView);
         img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
         progressDialog.dismiss();
      }
   };
   
   private boolean checkInternetConenction() {
      // get Connectivity Manager object to check connection
      ConnectivityManager connec =(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
      
      // Check for network connections
      if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
      
      connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
      connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
      connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
         Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
         return true;
      }else if (
      connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
      connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
         Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
         return false;
      }
      return false;
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}
=================================================================================================

Here is the content of 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:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UI Animator Viewer"
      android:id="@+id/textView"
      android:textSize="25sp"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:textColor="#ff36ff15"
      android:textIsSelectable="false"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="76dp" />

</RelativeLayout>

Here is the content of Strings.xml.

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>

Here is the content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.tutorialspoint.myapplication" >
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
        </activity>
        
    </application>
</manifest>

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:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UI Animator Viewer"
      android:id="@+id/textView"
      android:textSize="25sp"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView"
      android:textColor="#ff36ff15"
      android:textIsSelectable="false"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Button"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="76dp" />

</RelativeLayout>

 

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s