Demand analysis:

In the process of APP development, sharing and forwarding are generally required, such as sharing to QQ and wechat, etc. Here, I use the shareAPI of Android system, and I can directly obtain all apps that provide sharing interfaces in the phone through ResolveInfo to realize the sharing function.

First of all, let me show you the effect picture on the phone:

Reference sample code download address:

Download.csdn.net/download/qq…

XML layout file

share_dialog.xml

<? xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/shape_circle_dialog_bg"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="Share with..." />

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <GridView
                android:id="@+id/sharePopupWindow_gridView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="none" />
        </LinearLayout>
    </HorizontalScrollView>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:alpha="0.3"
        android:background="# 666" />

    <TextView
        android:id="@+id/sharePopupWindow_close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dp"
        android:text="Cancel"
        android:textSize="16sp" />

</LinearLayout>
Copy the code

appinfo_item.xml


      
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp">
    
    <ImageView
        android:id="@+id/appinfo_item_icon"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/appinfo_item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:textSize="12sp"
        android:text="Share with..."/>
</LinearLayout>
Copy the code

In res/values/styles.xml, add the following code for the pop-up background effect

<style name="circleDialog" parent="android:style/Theme.Dialog">
        <! -- Transparent background, set rounded corner dialog box must set transparent background, otherwise there will be small background color blocks -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <! -- No title -->
        <item name="android:windowNoTitle">true</item>
        <! -- Background blur -->
        <item name="android:backgroundDimEnabled">true</item>
</style>
Copy the code

Write an implementation class appInfo.java to store application information

package com.t20.sharedemo.entity;

import android.graphics.drawable.Drawable;

public class AppInfo {
	 private String pkgName;
	    private String launchClassName;
	    private String appName;
	    private Drawable appIcon;

	    public String getPkgName(a) {
	        return pkgName;
	    }

	    public void setPkgName(String pkgName) {
	        this.pkgName = pkgName;
	    }

	    public String getLaunchClassName(a) {
	        return launchClassName;
	    }

	    public void setLaunchClassName(String launchClassName) {
	        this.launchClassName = launchClassName;
	    }

	    public String getAppName(a) {
	        return appName;
	    }

	    public void setAppName(String appName) {
	        this.appName = appName;
	    }

	    public Drawable getAppIcon(a) {
	        return appIcon;
	    }

	    public void setAppIcon(Drawable appIcon) {
	        this.appIcon = appIcon; }}Copy the code

Rewrite PopupWindow control, custom share popover

SharePopupWindow.java

package com.t20.sharedemo.view;

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

import com.t20.sharedemo.R;
import com.t20.sharedemo.adapter.AppInfoAdapter;
import com.t20.sharedemo.entity.AppInfo;
import com.t20.sharedemo.util.ShareUtil;

import android.app.ActionBar.LayoutParams;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class SharePopupWindow extends PopupWindow {

	// How many rows to display
	private static final int APP_SIZE = 8;
	
	private View mMenuView; 
    private GridView mGridView;
    private TextView mTextViewClose;
    private AppInfoAdapter mAdapter;
    private Intent shareIntent;
    
    private List<AppInfo> mAppinfoList;
    private List<GridView> mGridViewList;
       
    / * * * *@param context
     * @paramShareContent The content to share */
    public SharePopupWindow(final Context context,final String shareContent) {
    	super(context); 
    	LayoutInflater inflater = (LayoutInflater) context  .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
        mMenuView = inflater.inflate(R.layout.share_dialog, null); 
        // Get the control
        mGridView=(GridView) mMenuView.findViewById(R.id.sharePopupWindow_gridView);
        mTextViewClose=(TextView) mMenuView.findViewById(R.id.sharePopupWindow_close);
        // Get the app with the sharing function
        shareIntent = new Intent(Intent.ACTION_SEND);
        //shareIntent.setType("text/plain"); / / plain text
        shareIntent.setType("* / *");  
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareContent);
        mAppinfoList = ShareUtil.getShareAppList(context, shareIntent);
        
        / / the GridView
        mAdapter=new AppInfoAdapter(context, mAppinfoList);
        mGridView.setAdapter(mAdapter);
        
        / / modify the GridView
        changeGridView(context);
        
        mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<? > parent, View view,int position,
					long id) {
				// TODO Auto-generated method stub
				AppInfo appInfo=mAppinfoList.get(position);
				Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setComponent(new ComponentName(appInfo.getPkgName(), appInfo.getLaunchClassName()));
                //intent.setType("text/plain"); / / plain text
                intent.setType("* / *"); intent.putExtra(Intent.EXTRA_TEXT, shareContent); context.startActivity(intent); }});// Cancel button
        mTextViewClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stubdismiss(); }});// Set SelectPicPopupWindow's View
        this.setContentView(mMenuView);  
        // Set the width of the SelectPicPopupWindow popup form
        this.setWidth(LayoutParams.FILL_PARENT);  
        // Set the height of the SelectPicPopupWindow popup form
        this.setHeight(LayoutParams.WRAP_CONTENT);  
        // Set SelectPicPopupWindow to pop up the form clickable
        this.setFocusable(true); 
		// Set the window outside can also click (click outside, the window can close)
        this.setOutsideTouchable(true);
        // Set SelectPicPopupWindow to pop up the form animation
        this.setAnimationStyle(R.style.circleDialog);  
        // instantiate a ColorDrawable color to translucency
        ColorDrawable dw = new ColorDrawable(0x00000000);  
        // Sets the background of the SelectPicPopupWindow popup form
        this.setBackgroundDrawable(dw); 
	}
    
    /** * Change the GridView to a single horizontal row */
    private void changeGridView(Context context) {
        / / width of the item
        int itemWidth = dip2px(context, 100);
        // The interval between items
        int itemPaddingH = dip2px(context, 1);
        int size = mAppinfoList.size();
        // Calculate the GridView width
        int gridviewWidth = size/2 * (itemWidth + itemPaddingH);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        mGridView.setLayoutParams(params);
        mGridView.setColumnWidth(itemWidth);
        mGridView.setHorizontalSpacing(itemPaddingH);
        mGridView.setStretchMode(GridView.NO_STRETCH);
        mGridView.setNumColumns(size/2);
    }
    
    /** * Switch from dp units to px(pixels) * based on the phone's resolution@paramContext *@param* dpValue dp value@returnPx value * /
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5 f); }}Copy the code

4. Write a utility class to get all the apps with the sharing function on the phone

ShareUtil.java

package com.t20.sharedemo.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.ArrayList;
import java.util.List;

import com.t20.sharedemo.entity.AppInfo;

public class ShareUtil {
	/** * Get a list of all shareable apps */
    public static ArrayList<AppInfo> getShareAppList(Context context, Intent intent) {
        ArrayList<AppInfo> shareAppInfos = new ArrayList<AppInfo>();
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> resolveInfos = getShareApps(context);
        if (null == resolveInfos) {
            return null;
        } else {
            for (ResolveInfo resolveInfo : resolveInfos) {
                AppInfo appInfo = newAppInfo(); appInfo.setPkgName(resolveInfo.activityInfo.packageName); appInfo.setLaunchClassName(resolveInfo.activityInfo.name); appInfo.setAppName(resolveInfo.loadLabel(packageManager).toString()); appInfo.setAppIcon(resolveInfo.loadIcon(packageManager)); shareAppInfos.add(appInfo); }}return shareAppInfos;
    }

    /** * Query the list of apps that support sharing */
    public static List<ResolveInfo> getShareApps(Context context) {    
        List<ResolveInfo> mApps = new ArrayList<ResolveInfo>();  
        Intent intent = new Intent(Intent.ACTION_SEND, null);  
        intent.addCategory(Intent.CATEGORY_DEFAULT);  
        //intent.setType("text/plain"); / / plain text
        intent.setType("* / *");  
        PackageManager pManager = context.getPackageManager();  
        mApps = pManager.queryIntentActivities(intent,PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);  
        returnmApps; }}Copy the code

6. I use a GridView to display app sharing ICONS, so I need to write a GridView adapter

AppInfoAdapter.java

package com.t20.sharedemo.adapter;

import java.util.List;

import com.t20.sharedemo.R;
import com.t20.sharedemo.entity.AppInfo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AppInfoAdapter extends BaseAdapter {

	private Context context;
	private List<AppInfo> mAppinfoList;
	private OnItemClickListener mOnItemClickLitener;

	public AppInfoAdapter(Context context, List<AppInfo> mAppinfoList) {
		super(a);this.context = context;
		this.mAppinfoList = mAppinfoList;
	}

	@Override
	public int getCount(a) {
		// TODO Auto-generated method stub
		return mAppinfoList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@SuppressLint("NewApi")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		AppInfo appInfo = mAppinfoList.get(position);
		// Load the layout
		View view;
		ViewHolder viewHolder;
		if (convertView == null) {
			view = LayoutInflater.from(context).inflate(R.layout.appinfo_item, null);
			viewHolder = new ViewHolder(view);
			// Store the ViewHolder in the View
			view.setTag(viewHolder);
		} else {
			view = convertView;
			// Retrieve the ViewHolder
			viewHolder = (ViewHolder) view.getTag();

		}
		// Sets the value of the control
		viewHolder.imageViewIcon.setImageDrawable(appInfo.getAppIcon());
		String name=appInfo.getAppName();
		viewHolder.textViewName.setText(name);
		return view;
	}

	class ViewHolder {
		ImageView imageViewIcon;
		TextView textViewName;
		
		public ViewHolder(View view) {
			this.imageViewIcon = (ImageView) view.findViewById(R.id.appinfo_item_icon);
			this.textViewName = (TextView) view.findViewById(R.id.appinfo_item_name); }}}Copy the code

Mainactivity. Java activity code is relatively simple, directly define the SharePopupWindow window

package com.t20.sharedemo;

import com.t20.sharedemo.view.SharePopupWindow;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

	private RelativeLayout mLayoutRoot;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 1, hide the title bar, set before loading the layout (compatible with Android2.3.3 version)
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// hide the status bar
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		// Get the root layout
		mLayoutRoot=(RelativeLayout) findViewById(R.id.mainActivity_root);
	}
	/** * click to share */
	public void share(View view){
		// Set the content to share
		String shareContent=Studio "# god code # blog: https://blog.csdn.net/qq15577969";
		SharePopupWindow spw = new SharePopupWindow(this, shareContent);
		// Display window
		spw.showAtLocation(mLayoutRoot, Gravity.BOTTOM, 0.0); }}Copy the code