Android 剪贴板操作

前言

百度下找资料发现居然有人分享了文章还要收钱才能看,气不过,自己写个分享,路过的觉得有用点个赞

近期开发遇到开发的一个功能,跟淘宝的分享链接一样,复制完分享链接后分享给别人,打开我们的APP要弹窗去做下一步操作。这里有个要注意的地方,怎么区分是在自己的app复制还是在别的app复制。

第一步

复制

       /**
     *
     * @param context Context
     * @param string String 复制的内容
     * @param action Function0? 复制完成后执行的方法
     */
    fun copyClip(context: Context, string: String, action: (() -> Unit)?) {
        try {
            val mClipData = ClipData.newPlainText("Label", string)
            (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?)?.run {
                setPrimaryClip(mClipData)
                action?.invoke()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

注意 这里的“Label”是关键,判断是否是自己app复制的就靠这个字段

第二步

获取复制的内容

    fun getClipData():Boolean{
        try {
            val cm = UIUtils.getContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            if (cm.hasPrimaryClip() && cm.primaryClip?.itemCount!! >0 && cm.hasText()) {
                val label = cm.primaryClip!!.description.label
                if ("Label" == label) { //通过先前设置的字段来判断是否是在自己的app复制
                    //来自自己app的复制内容
                    Log.d(TAG, "ClipboardManager:" + "来自自己app的复制内容")
                    return false
                } else {
                    val data = cm.primaryClip
                    val item = data!!.getItemAt(0)
                    val content = item.text.toString()
                    if (content.isNotEmpty()){
                        Log.d(TAG, "ClipboardManager:来自其他app的复制内容--$content")
                        //清空剪贴板,一般获取完数据之后需要清空
                        cm.setPrimaryClip(ClipData.newPlainText(null,null))
                        return true
                    }
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        return false
    }

都封装成方法,方便调用

第三步

一般有这种操作都需要判断是否从后台跳前台,直接上代码

package com.ugreen.nas.manager;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;

import java.util.ArrayList;

public final class ActivityStackManager implements Application.ActivityLifecycleCallbacks {

    private static volatile ActivityStackManager sInstance;
    private static long startedActivityCount = 0l;

    private final ArrayMap mActivitySet = new ArrayMap<>();
    private ArrayList mOnBackgroundListeners = new ArrayList<>();


    /** 当前应用上下文对象 */
    private Application mApplication;
    /** 当前 Activity 对象标记 */
    private String mCurrentTag;

    private ActivityStackManager() {}

    public static ActivityStackManager getInstance() {
        // 加入双重校验锁
        if(sInstance == null) {
            synchronized (ActivityStackManager.class) {
                if(sInstance == null){
                    sInstance = new ActivityStackManager();
                }
            }
        }
        return sInstance;
    }

    public void init(Application application) {
        mApplication = application;
        application.registerActivityLifecycleCallbacks(this);
    }

    /**
     * 获取 Application 对象
     */
    public Application getApplication() {
        return mApplication;
    }

    /**
     * 获取栈顶的 Activity
     */
    public Activity getTopActivity() {
        return mActivitySet.get(mCurrentTag);
    }

    /**
     * 销毁所有的 Activity
     */
    public void finishAllActivities() {
        finishAllActivities((Class) null);
    }

    /**
     * 销毁所有的 Activity,除这些 Class 之外的 Activity
     */
    @SafeVarargs
    public final void finishAllActivities(Class... classArray) {
        String[] keys = mActivitySet.keySet().toArray(new String[]{});
        for (String key : keys) {
            Activity activity = mActivitySet.get(key);
            if (activity != null && !activity.isFinishing()) {
                boolean whiteClazz = false;
                if (classArray != null) {
                    for (Class clazz : classArray) {
                        if (activity.getClass() == clazz) {
                            whiteClazz = true;
                        }
                    }
                }
                // 如果不是白名单上面的 Activity 就销毁掉
                if (!whiteClazz) {
                    activity.finish();
                    mActivitySet.remove(key);
                }
            }
        }
    }

    @SafeVarargs
    public final void finishSpeicActivities(Class... classArray) {
        try {
            String[] keys = mActivitySet.keySet().toArray(new String[]{});
            for (String key : keys) {
                Activity activity = mActivitySet.get(key);
                if (activity != null && !activity.isFinishing()) {
                    boolean whiteClazz = false;
                    if (classArray != null) {
                        for (Class clazz : classArray) {
                            if (activity.getClass() == clazz) {
                                whiteClazz = true;
                            }
                        }
                    }
                    // 如果不是白名单上面的 Activity 就销毁掉
                    if (whiteClazz) {
                        activity.finish();
                        mActivitySet.remove(key);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取一个对象的独立无二的标记
     */
    private static String getObjectTag(Object object) {
        // 对象所在的包名 + 对象的内存地址
        return object.getClass().getName() + Integer.toHexString(object.hashCode());
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        mCurrentTag = getObjectTag(activity);
        mActivitySet.put(getObjectTag(activity), activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        mCurrentTag = getObjectTag(activity);
        startedActivityCount++;
        if (1 == startedActivityCount) {
            for (OnBackgroundListener onBackgroundListener : mOnBackgroundListeners) {
                onBackgroundListener.onActivityChanged(false);
            }
        }
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        mCurrentTag = getObjectTag(activity);
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {}

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        startedActivityCount--;
        if (0 == startedActivityCount) {
            for (OnBackgroundListener onBackgroundListener : mOnBackgroundListeners) {
                onBackgroundListener.onActivityChanged(true);
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        mActivitySet.remove(getObjectTag(activity));
        if (getObjectTag(activity).equals(mCurrentTag)) {
            // 清除当前标记
            mCurrentTag = null;
        }
    }

    public interface OnBackgroundListener {
        void onActivityChanged(boolean background);
    }

    public void registerObserver(OnBackgroundListener observer) {
        if (!mOnBackgroundListeners.contains(observer)) {
            mOnBackgroundListeners.add(observer);
        }
    }

    public void unregisterObserver(OnBackgroundListener observer) {
        mOnBackgroundListeners.remove(observer);
    }
}

怎么调用

ActivityStackManager.getInstance().registerObserver(new ActivityStackManager.OnBackgroundListener() {
            @Override
            public void onActivityChanged(boolean background) {
                Log.d(TAG, "background:" + (background ? "后台" : "前台"));
                if (!background) {
                 //这里去处理你的逻辑
                }
            }
        });

到这里就基本都搞定了,剩余的一些自己的逻辑就自己处理

你可能感兴趣的:(Android 剪贴板操作)