Apr 24, 2021

How add Share Button In Toolbar - Android Studio - Androidpro.in

MainActivity.Java

package in.app.androidpro.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.File;

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.menu,menu);
       return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
       int id = item.getItemId();
       if (id == R.id.share){
           ApplicationInfo api = getApplicationContext().getApplicationInfo();
           String apkpath = api.sourceDir;
           Intent intent = new Intent(Intent.ACTION_SEND);
           intent.setType("aplication/vnd.android.package-archive");
           intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(apkpath)));
           startActivity(Intent.createChooser(intent,"ShareVia"));
       }
       return true;
    }
}

Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/share"
    android:title="Share"
    android:icon="@drawable/ic_baseline_share_24"
    app:showAsAction="always"/>
</menu>

Whatsapp Button works on Mobile Device only