Send File from android mobile to computer or pc using socket programing



Hear is the code which explain you how to send image or data using socket programming from android to pc or pc to android device. after learn this tutorial or demo i think you able to create chat or socket base application to connect pc or android device.

Hear i am create one android project at to send image to pc(server side) and another one is create java class file at pc or server side.


Code at server Side : java file FileServer.java
import java.io.*;
import java.net.*;

public class FileServer {

    public static void main(String[] args) throws IOException {
        int filesize=6022386; // 

        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;

       
        ServerSocket servsock = new ServerSocket(1149);
        while (true) {
          System.out.println("Waiting...");

          Socket sock = servsock.accept();
          System.out.println("Accepted connection hear : " + sock);

       // receive file
            byte [] mybytearray  = new byte [filesize];
            InputStream is = sock.getInputStream();
            FileOutputStream fos = new FileOutputStream("H:\\demo.jpg"); // 
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;

            // thanks to dhaval solanki
            do {
               bytesRead =
                  is.read(mybytearray, current, (mybytearray.length-current));
               if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead > -1);

            bos.write(mybytearray, 0 , current);
            bos.flush();
            long end = System.currentTimeMillis();
            System.out.println(end-start);
            bos.close();
          sock.close();
          }
    }

}


Android Side : activity_main.xml

Layout File :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <EditText
        android:layout_width="match_parent"
        android:id="@+id/ip_edt"
        android:layout_height="60dp" />
    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

    <TextView
        android:id="@+id/tvPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Path: " />

    <Button
        android:id="@+id/bBrowse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse" >
    </Button>

    <Button
        android:id="@+id/bSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

    <ImageView
        android:id="@+id/ivPic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ImageView>

</LinearLayout>


Android Class File : MainActivity.java

package com.materialexample;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import in.co.bhadreshtech.materialexample.R;

public class MainActivity extends AppCompatActivity {

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;
    private EditText ip_edt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ip_edt = (EditText) findViewById(R.id.ip_edt);
        System.out.println("34");
        img = (ImageView) findViewById(R.id.ivPic);
        System.out.println("36");
        ((Button) findViewById(R.id.bBrowse))
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        System.out.println("40");
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(
                                Intent.createChooser(intent, "Select Picture"),
                                SELECT_PICTURE);
                        System.out.println("47");
                    }
                });
        ;
        System.out.println("51");
        Button send = (Button) findViewById(R.id.bSend);
        final TextView status = (TextView) findViewById(R.id.tvStatus);

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                final Socket[] sock = new Socket[1];
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sock[0] = new Socket(ip_edt.getText().toString() + "", 1149);
                            File myFile = new File(selectedImagePath);
                            byte[] mybytearray = new byte[(int) myFile.length()];
                            FileInputStream fis = new FileInputStream(myFile);
                            BufferedInputStream bis = new BufferedInputStream(fis);
                            bis.read(mybytearray, 0, mybytearray.length);
                            OutputStream os = sock[0].getOutputStream();
                            System.out.println("Sending...");
                            os.write(mybytearray, 0, mybytearray.length);
                            os.flush();
                            sock[0].close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        System.out.println("Connecting...");

                    }
                });
                thread.start();
                // sendfile


            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                TextView path = (TextView) findViewById(R.id.tvPath);
                path.setText("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

Play video from url using VideoView in android



in this post you will learn how to play video from video url using Video View in your application, and hear i am not use MediaController but if you use then you can perform operation like play,pause,stop,e.t.c, video.

Class File : VideoViews.java
package com.materialexample;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.VideoView;
import in.co.bhadreshtech.materialexample.R;
public class VideoViews extends AppCompatActivity {
    ProgressBar progressBar = null;
    VideoView videoView1 = null;
    String videoUrl = "http://www.androidbegin.com/tutorial/AndroidCommercial.3gp";
    Context context = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_views);
        context = null;
        videoView1 = (VideoView) findViewById(R.id.video_view1);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        Uri videoUri = Uri.parse(videoUrl);
        videoView1.setVideoURI(videoUri);
        videoView1.start();
        progressBar.setVisibility(View.VISIBLE);
        videoView1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.start();
                mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int arg1,
                                                   int arg2) {
                        // TODO Auto-generated method stub
                        progressBar.setVisibility(View.GONE);
                        mp.start();
                    }
                });

            }
        });
    }
}


Layout File  : VideoViews.java

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.materialexample.VideoViews">

    <VideoView
        android:id="@+id/video_view1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="50dp"
        android:layout_height="50dp" />
</RelativeLayout>

How to display TextView as Circle in Android



  • Hear is the code which explain how to create textview with circle in Android.
  • First Create xml file and put in drawable folder .


XML File for Background :circuler_textview.xml

Declare Textview with background  circuler_textview .


<TextView
            android:layout_width="@dimen/mLblSearchIdeaLabel_font_size"
            android:layout_height="@dimen/mLblSearchIdeaLabel_font_size"
            android:layout_centerInParent="true"
            android:background="@drawable/circuler_textview"
            android:gravity="center"
            android:id="@+id/mLblSearchIdeaLabel"
            android:padding="@dimen/mLblLogOut_paddin"
            android:text="Searching Idea"
            android:textColor="@android:color/black"
            android:textSize="@dimen/item_swipe_left_indicator_font_size" />

What is The Intent ?

What is the intent explain with example ?
  • An intent is exactly describe its an intention to do an action.
  • An intent is basically a message to say you did or want to something to happen. But It depend on intents, your app or OS will listen it or react accordingly.
  • To listen for a intent( like the v, or an notification or sms received), you implement broadcast receiver.
  • An Intent are object of the android.content.intent type. And also intent can content data via a Bundle, and this data will be used by the receiver side component.
  • There are two type of intent.An android support two type intent one is the Implicit and another is the explicit

  • Implicit Intent : 
  • An implicit intent is the specify the action which should be performed an optionally data which provide the action.
  • For example, you may write to code for view web page.

Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.bhadreshtech.in"));
startActivity(intent);
  • if an implicit intent sent is sent to the android system, it search for all components which are registered for the specific action and the fitting data type.
  • If only one component is found then they select directly. If several components are identified by the Android System, the user will get a selection dialog and can decide which component should used for intent.
  • Implicit Intent : 
  • Explicit intents define the component which should be called by the Android System,by using java class as identifier .
  • Following should explain how to create explicit intent and send it to the android system. If the class specified in the intent represents and activity, the android system start it.
ntent intent=new Intent(this,ActivityTwo.class);
startActivity(intent);

  • Data transfer with intent between tow activities.
  • Lots of application allow to share data with other people, like whatsapp, facebook, twitter, e.t.c,..
  • Using bundle you can send data with intent with different different types.
  • For example, Sender Side : 

Intent intent = new Intent(context,ActivityTwo.class);
intent.putExtra("key","value");
startActivity(intent);
  • Receiver Side :
Bundle bundle = getIntent().getExtras();
String value=bundle.getString("key");

Create Browser using WebView with navigation button(Next and Previous) or reload button.

Hear is the code which explain, How to create Browser using WebView with navigation button Functionality.

Layout File : activity_detailed_news.xml


<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.bhadreshtech.Activity.DetailedNewsActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/mWebNews"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/linearLayout4">
        </WebView>
        <ImageView
            android:layout_width="wrap_content"
            android:src="@drawable/my_progress_indeterminate"
            android:id="@+id/mImgProgress"
            android:layout_centerInParent="true"
            android:layout_height="wrap_content" />
        <RelativeLayout
            android:id="@+id/linearLayout4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_alignTop="@+id/mImgRefresh"
                android:layout_alignBottom="@+id/mImgRefresh"
                android:layout_height="wrap_content"
                android:layout_toLeftOf="@+id/mImgRefresh"
                android:layout_toStartOf="@+id/mImgRefresh">
                <TextView
                    android:id="@+id/mLblPrevious"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_gravity="center_vertical"
                    android:padding="10dp"
                    android:gravity="center"
                    android:text="Previous"
                    android:textColor="@color/blue_light"
                    android:textSize="15dp" />
                <TextView
                    android:id="@+id/mLblNext"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:padding="10dp"
                    android:textColor="@color/blue_light"
                    android:gravity="center"
                    android:paddingLeft="20dp"
                    android:text="Next"
                    android:textSize="15dp" />
            </LinearLayout>
            <ImageView
                android:id="@+id/mImgRefresh"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_gravity="right"
                android:padding="10dp"
                android:src="@drawable/reload_icon"
                android:textSize="15dp" />
        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>


Class File : DetailedNewsActivity


package com.bhadreshtech.Activity;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.bhadreshtech.R;

public class DetailedNewsActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mLblTitleAction;
    private ImageView mImgMenuToggle;
    private ImageView mImgAction;
    private String url = "http://www.google.com";
    private int from = 0;
    private WebView mWebNews;
    private ImageView mImgBacks, mImgRefresh;
    private TextView mLblNext, mLblPrevious;
    private ImageView mImgProgress;
    private boolean blag_progress;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_news);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            url = bundle.getString("url") + "";
            from = bundle.getInt("from");
        }
        initializeView();
        setClickEvent();

    }

    private void setClickEvent() {
        mImgRefresh.setOnClickListener(this);
        mLblNext.setOnClickListener(this);
        mLblPrevious.setOnClickListener(this);
        mImgMenuToggle.setOnClickListener(this);
    }

    private void initializeView() {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
        getSupportActionBar().setCustomView(R.layout.custome_actiobar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        mLblTitleAction = (TextView) findViewById(R.id.mLblTitleAction);
        mLblTitleAction.setText("News Detail");
        mImgProgress = (ImageView) findViewById(R.id.mImgProgress);
        mImgProgress.setVisibility(View.VISIBLE);
        mImgMenuToggle = (ImageView) findViewById(R.id.mImgMenuToggle);
        mImgMenuToggle.setImageDrawable(getResources().getDrawable(R.drawable.cloase_bt));
        mImgAction = (ImageView) findViewById(R.id.mImgAction);
        mImgAction.setVisibility(View.INVISIBLE);
        mImgRefresh = (ImageView) findViewById(R.id.mImgRefresh);
        mLblNext = (TextView) findViewById(R.id.mLblNext);
        mLblPrevious = (TextView) findViewById(R.id.mLblPrevious);
        intializeWebView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mImgRefresh:
                if (blag_progress) {
                    mWebNews.onPause();
                    mImgProgress.setVisibility(View.GONE);
                    mImgRefresh.setImageDrawable(getResources().getDrawable(R.drawable.reload_icon));
                    blag_progress = false;
                } else {
                    mImgProgress.setVisibility(View.VISIBLE);
                    mWebNews.reload();
                    mImgRefresh.setImageDrawable(getResources().getDrawable(R.drawable.close_icon));
                    blag_progress = true;
                }
                break;
            case R.id.mImgMenuToggle:
                this.finish();
                break;
            case R.id.mLblNext:
                if (mWebNews.canGoForward()) {
                    mWebNews.goForward();
                }
                break;
            case R.id.mLblPrevious:
                if (mWebNews.canGoBack()) {
                    mWebNews.goBack();
                }
                break;
        }
    }

    private void intializeWebView() {
        mWebNews = (WebView) findViewById(R.id.mWebNews);
        mWebNews.getSettings().setJavaScriptEnabled(true);
        mWebNews.loadUrl(url);
        //mWebNews.loadUrl("file:///android_asset/ppp1.html");
        mWebNews.setWebViewClient(new WebViewClient());
        mWebNews.setInitialScale(1);
        mWebNews.getSettings().setBuiltInZoomControls(true);
        mWebNews.getSettings().setUseWideViewPort(true);
        mWebNews.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress >= 80) {
                    mImgRefresh.setImageDrawable(getResources().getDrawable(R.drawable.reload_icon));
                    blag_progress = false;
                    mImgProgress.setVisibility(View.GONE);
                } else {
                    mImgRefresh.setImageDrawable(getResources().getDrawable(R.drawable.close_icon));
                    blag_progress = true;
                    mImgProgress.setVisibility(View.VISIBLE);
                }

            }
        });

    }


}

Play video from resource file in Android using VideoView.

Hear is the code demo for play video from android resource "raw" directory,


Layout code : activity_video_views.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.materialexample.VideoViews">
    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


Activity Code : VideoViews

package com.materialexample;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.MediaController;
import android.widget.VideoView;
import in.co.materialexample.R;

public class VideoViews extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_views);
        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        int resID = getResources().getIdentifier("video1", "raw", this.getPackageName());
        Uri video1 = Uri.parse("android.resource://" + this.getPackageName() + "/" + resID); //do not add any extension
        videoView.setMediaController(null);
        videoView.stopPlayback();
        videoView.setVideoURI(video1);
        // Log.i("video1..", ".." + video1 + ".." + resID);
        videoView.requestFocus();
        videoView.start();

    }
}