Skip to main content

Share Application - Any social  app 

Facebook,Twitter,Instagram,Youtube,Google+....etc.

 

                                   Pate Prashant 

 

Android Code For share any application.

Share code for Video,Image,Text.  share on (Twitter,Facebook,Instagram,Google+,Youtube)


Some packeges of application name

Application Name                                                Package Name

Twitter                                 com.twitter.android             
Facebook                             com.facebook.katana
Instagram                            com.instagram.android
Google+                              google
Youtube                              com.google.android.youtube


Java file :

MainActivity.java


// Just change application packege name for share 


package com.prince.apps.shareall;

import java.io.File;
import java.util.List;

import com.kpbird.androidinstagramdemo.R;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    String outputFile = "/storage/emulated/0/Download/video.mp4";

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

    // Listener for Button Clicked - Defined in button:onClilck property
    public void buttonClicked(View v) {

        // Let's check Instagram is installed or not
        if (!appInstalledOrNot()) {
            Toast.makeText(this, "Instagram Application is not installed",Toast.LENGTH_LONG).show();
            return;
        }

        if (v.getId() == R.id.btngallery) {
            shareFromGallery(); // share image from gallery

        } else if (v.getId() == R.id.btnsdcard) {
            shareFromSDCard(); // share image from sdcard
        }
        else if(v.getId() == R.id.btnpath)
        {
            // instagram();
                   
                            new Handler().post(new Runnable()
                            {           
                                @Override
                                public void run()
                                {
                                    String newPath=getVideoContentUriFromFilePath(MainActivity.this, outputFile);
                                    Intent intent = new Intent(Intent.ACTION_SEND);
                                             intent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Title");
                                        //intent.setAction(Intent.ACTION_SEND);
                                        intent.setType("video/mp4");
                                        intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(newPath));
                                        try
                                        {
                                            startActivity(Intent.createChooser(intent,"Upload video via:"));
                                        }
                                        catch (android.content.ActivityNotFoundException ex)
                                        {
           
                                        }
                                }       
                            });
        }
                       
    }

    /*
     * This method use PackageManager Class to check for instagram package.
     * */
    private boolean appInstalledOrNot() {

        boolean app_installed = false;
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo("com.instagram.android", 1);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        }
        return app_installed;
    }
   
    /*This method invoke gallery or any application which support image/* mime type */
    private void shareFromGallery(){
        Intent intent = new Intent();
        intent.setType("video/*");
    //    intent.setType("image/*");
       
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
    }
    /*this method share test.jpg file from sd card */
    private void shareFromSDCard(){
        shareInstagram(Uri.parse("file://"+Environment.getExternalStorageDirectory()+"/test.jpg"));
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   
            Uri uri = data.getData();
             shareInstagram(uri);   
    }
   
    /* this mathod actually share image to Instagram, It accept Uri */
    private void shareInstagram(Uri uri){
       
        /// Method 1 : Optimize
        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("video/*"); // set mime type
        shareIntent.putExtra(Intent.EXTRA_STREAM,uri); // set uri
        shareIntent.setPackage("com.instagram.android");
        startActivity(shareIntent);
       
       
        // Intent for action_send 
//        Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
//        shareIntent.setType("image/*"); // set mime type
//        shareIntent.putExtra(Intent.EXTRA_STREAM,uri); // set uri
//       
//        //following logic is to avoide option menu, If you remove following logic then android will display list of application which support image/* mime type
//        PackageManager pm = getPackageManager();
//        List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
//        for (final ResolveInfo app : activityList) {
//            if ((app.activityInfo.name).contains("instagram")) { // search for instagram from app list
//                final ActivityInfo activity = app.activityInfo;
//                final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
//                shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                shareIntent.setComponent(name); // set component
//                startActivity(shareIntent);
//                break;
//           }
//        }
    }
    public void instagram()
     {
     
      Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
      shareIntent.setType("video/*");                

      final ContentResolver cr = getContentResolver();
     
      final String[] p1 = new String[]
      {
          MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.TITLE, MediaStore.Images.ImageColumns.DATE_TAKEN
        
      };
     
      Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");

      /*if (c1.moveToFirst() ) {
          Log.i("Teste", "last picture (" + c1.getString(1) + ") taken on: " + new Date(c1.getLong(2)));
      }*/

      //Log.i("Caminho download imagem", "file://"+Environment.getExternalStorageDirectory()+ "/Tubagram/"  + c1.getString(1) + ".png");

      shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(outputFile)));
      shareIntent.setPackage("com.instagram.android");
      c1.close();

      startActivity(shareIntent);
     
     }
   
   
   
    public static String getVideoContentUriFromFilePath(Context ctx, String filePath) {

          ContentResolver contentResolver = ctx.getContentResolver();
          String videoUriStr = null;
             long videoId = -1;
             Log.d("first log","Loading file " + filePath);


             // This returns us content://media/external/videos/media (or something like that)
             // I pass in "external" because that's the MediaStore's name for the external
             // storage on my device (the other possibility is "internal")
             Uri videosUri = MediaStore.Video.Media.getContentUri("external");

             Log.d("second log","videosUri = " + videosUri.toString());

             String[] projection = {MediaStore.Video.VideoColumns._ID};

             // TODO This will break if we have no matching item in the MediaStore.
             Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
             cursor.moveToFirst();

             int columnIndex = cursor.getColumnIndex(projection[0]);
             videoId = cursor.getLong(columnIndex);

             Log.d("third log","Video ID is " + videoId);
             cursor.close();
             if (videoId != -1 ) videoUriStr = videosUri.toString() + "/" + videoId;
             return videoUriStr;
         }
   
   
}
















Layout xml file





 <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=".MainActivity" >

    <Button
        android:id="@+id/btngallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:onClick="buttonClicked"
        android:text="Share from Gallery" />

    <Button
        android:id="@+id/btnsdcard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btngallery"
        android:onClick="buttonClicked"
        android:text="Share from SD Card" />

    <Button
        android:id="@+id/btnpath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btngallery"
        android:layout_marginTop="53dp"
        android:onClick="buttonClicked"
        android:text="Share path" />

</RelativeLayout>

 AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kpbird.androidinstagramdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.prince.apps.shareall.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>









Comments

Popular posts from this blog

Laravel Free Admin Panel UI and Code

Thanks for share  https://github.com/the-control-group/voyager V oyager - The Missing Laravel Admin Made with  ❤️  by  The Control Group Website & Documentation:  https://voyager.devdojo.com/ Video Tutorial Here:  https://voyager.devdojo.com/academy/ Join our Slack chat:  https://voyager-slack-invitation.herokuapp.com/ View the Voyager Cheat Sheet:  https://voyager-cheatsheet.ulties.com/ Laravel Admin & BREAD System (Browse, Read, Edit, Add, & Delete), supporting Laravel 6 and newer! Want to use Laravel 5? Use  Voyager 1.3 Installation Steps 1. Require the Package After creating your new Laravel application you can include the Voyager package with the following command: composer require tcg/voyager 2. Add the DB Credentials & APP_URL Next make sure to create a new database and add your database credentials to your .env file: DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB...

How To Install And Setup Laravel Latest Version On Windows 10 Using XAMPP

How to install Laravel on Windows using XAMPP Laravel, one of the best PHP framework is getting more popular among developers all around the world. The Model-View-Controller architecture and blade templating engine made Laravel simple and powerful. Here we are going to discuss the steps of installation and setup of Laravel 5.7 on Windows 10 using XAMPP. Installation Follow the steps below to start installing Laravel 5.7 on Windows 10: 1. Install XAMPP XAMPP is the most popular PHP development environment.XAMPP is a completely free, easy to install Apache distribution containing MariaDB, PHP, and Perl. The XAMPP open source package has been set up to be incredibly easy to install and to use. XAMPP can be easily installed using the link below. https://www.apachefriends.org/download.html Laravel 5.7 requires PHP >= 7.1.3. Download the latest version (7.3.3/PHP 7.3.3). I have shown some screenshots of the installation steps below. 2. Start Apache and MySQ...