Android Share Action

By Kunal Kapoor
17-05-2018
260

Sharing is an important feature in modern day smartphones. It enables users to quickly send some data to other users through a wide range of apps and servies like social media, bluetooth and even Wifi enabled apps also.


In this project we will be demonstrating you how to share a text from your android app:

Overview of project:



First create a simple layout containing a button (and an edidtext, as per your needs): activity_main.xml:

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ourcoaching.simpleshareaction.MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share Website"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />android.support.constraint.ConstraintLayout
> 



Now in Java file, instantiate the button and create an onclick listener for it. Also define a string to be send

private String Website_url="www.ourcoaching.com";

button=(Button)findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ShareWebPage();
}
});


In the ShareWebpage() method, define an Intent to send data. Put the string data to be send into that intent. Set the type to text/plain to enable normal text data to be send

Intent share=new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_TEXT,Website_url);
share.setType("text/plain");


Finally call startActivity to send share the data.

startActivity(share);


Complete Java Code: MainActivity.java:

package com.ourcoaching.simpleshareaction;

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

public class MainActivity extends AppCompatActivity {

private String Website_url="www.ourcoaching.com";
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button=(Button)findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ShareWebPage();
}
});
}

private void ShareWebPage() {
Intent share=new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_TEXT,Website_url);
share.setType("text/plain");
startActivity(share);
}
}



Download the code from GitHub



Related Tutorials