Android进阶之路 - 常用小功能

以下的所有小功能都是我在项目长期的开发中使用的,为了方便每个app的开发,故在此做些记录,方便你我他~

基友篇

  • Android进阶之路 - 常用小工具
  • Android项目归纳 - 常见小问题与解决方式

功能列表(The smile is the greatest strength)

    • 俩次返回,退出应用
    • 内容复制,粘贴
    • 获取屏幕宽高度
    • 获取软键盘的高度
    • 自动弹出软键盘
    • 隐藏软键盘
    • 监听软键盘状态(弹出收回)
    • 防暴力点击方法
    • 防暴力点击方法(自己设置点击的间隔时间)
    • 输入的小写字母自动转换为大写字母
    • 震动动画
    • 设置Layout外边距
    • 设置同一控件下,不同文本的展示效果(html方法)
    • 获取当前项目中图片的具体存储位置
    • 检测手机是否安装微信、QQ、支付宝、微博
    • 唤醒app
    • 通过url 跳转对应的三方app主件(我的使用场景:webview跳转三方支付时唤起本地app)


Show Time ~

俩次返回,退出应用

  /**
     * 二次返回提醒客户
     */
    long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                toast("再次点击退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

内容复制,粘贴

//存储的概念
//复制 - 输入 
ClipboardManager cbm=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
cbm.setText("这是剪贴板的内容");

//粘贴 - 输出
ClipboardManager cbm=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
edit1.setText(cbm.getText());

获取屏幕宽高度

    /**
     * 获取宽度
     * */
    public static int getScreenWith(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 获取高度
     * */
    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

获取软键盘的高度

     et.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
            //当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //获取当前界面可视部分
                MainActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight =  MainActivity.this.getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的, 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                Log.d("Keyboard Size", "Size: " + heightDifference);
            } 
	 });

自动弹出软键盘

/**
* 查看当前键盘状态, 如显示则影藏,如影藏则展示~
*/
private void showKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(editText, 0);
    }

隐藏软键盘

方式一:

   /**
    *隐藏软键盘
    */
    void hintKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), 0);
        }
    }

方式二:

  /**
     * des:隐藏软键盘,这种方式参数为activity
     */
    public static void hideInputForce(Activity activity) {
        if (activity == null || activity.getCurrentFocus() == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

监听软键盘状态(弹出收回)

Android开发之监听软键盘状态(弹出收回)

  • 自定义监听类 KeyboardStateObserver(可直接Copy使用)
package 自己的当前的包名
/**
 * @author MrLiu
 * @date 2019/9/12
 * desc
 */
import android.app.Activity;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

public class KeyboardStateObserver {

    private static final String TAG = KeyboardStateObserver.class.getSimpleName();

    public static KeyboardStateObserver getKeyboardStateObserver(Activity activity) {
        return new KeyboardStateObserver(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private OnKeyboardVisibilityListener listener;

    public void setKeyboardVisibilityListener(OnKeyboardVisibilityListener listener) {
        this.listener = listener;
    }

    private KeyboardStateObserver(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                if (listener != null) {
                    listener.onKeyboardShow();
                }
            } else {
                if (listener != null) {
                    listener.onKeyboardHide();
                }
            }
            usableHeightPrevious = usableHeightNow;
            Log.d(TAG,"usableHeightNow: " + usableHeightNow + " | usableHeightSansKeyboard:" + usableHeightSansKeyboard + " | heightDifference:" + heightDifference);
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);

        Log.d(TAG,"rec bottom>" + r.bottom + " | rec top>" + r.top);
        return (r.bottom - r.top);// 全屏模式下: return r.bottom
    }

    public interface OnKeyboardVisibilityListener {
        void onKeyboardShow();

        void onKeyboardHide();
    }
}

  • 使用方式

注意:此方式必须在弹出键盘时候,使页面原有布局发生变动,所以如果不起作用的话可以试着在AndroidManifest.xml文件中设置android:windowSoftInputMode=”adjustResize|stateHidden“”

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

     KeyboardStateObserver.getKeyboardStateObserver(this).
             setKeyboardVisibilityListener(new KeyboardStateObserver.OnKeyboardVisibilityListener() {
         @Override
         public void onKeyboardShow() {
             Toast.makeText(MainActivity.this,"键盘弹出",Toast.LENGTH_SHORT).show();
         }

         @Override
         public void onKeyboardHide() {
             Toast.makeText(MainActivity.this,"键盘收回",Toast.LENGTH_SHORT).show();
         }
     });
 }

防暴力点击方法

    /**
     * 防暴力点击方法
     * lastClickTime = 0
     */
    public static Boolean noDoubleClick() {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastClickTime > 300) {
            lastClickTime = currentTimeMillis;
            //可以点击
            return true;
        }
        return false;
    }

防暴力点击方法(自己设置点击的间隔时间)

   /**
     * 防暴力点击方法
     * @param spaceTime 间隔时间(ms)
     *  lastClickTime = 0
     */
    public static Boolean noDoubleClick(long spaceTime) {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastClickTime > spaceTime) {
            lastClickTime = currentTimeMillis;
            //可以点击
            return true;
        }
        return false;
    }

输入的小写字母自动转换为大写字母

public class A2AChange extends ReplacementTransformationMethod {
    @Override
    protected char[] getOriginal() {
        char[] aa = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
        return aa;
    }

    @Override
    protected char[] getReplacement() {
        char[] cc = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
        return cc;
    }
}

使用方式

textView.setTransformationMethod(new A2AChange());

震动动画

 private void setMsgAnimator() {
   ObjectAnimator a = ObjectAnimator.ofFloat(rlMsgCenter, "translationX", 0, 10);
        a.setInterpolator(new LinearInterpolator());
        a.setDuration(40);
        a.setRepeatCount(20);
        a.setRepeatMode(ObjectAnimator.REVERSE);
        a.start();
 }

设置Layout外边距

 public void margin(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

设置同一控件下,不同文本的展示效果(html方法)

//主要代码
 Html.fromHtml("第一段文本信息" + "" + "第二段文本信息(为灰色)" + "")

//使用方式(如要设置颜色,可以如第二段一般进行颜色填充~)
 mContext.setText(Html.fromHtml("希望" + "" + "我们都不会老" + ""));

//展示结果
 希望 为 黑色字体
 我们不会老 为 灰色字体

获取当前项目中图片的具体存储位置

/**R.mipmap.ic_status_add为项目中的图片*/
String resourcePackageName = getResources().getResourcePackageName(R.mipmap.ic_status_add);
String resourceTypeName = getResources().getResourceTypeName(R.mipmap.ic_status_add);
String resourceEntryName = getResources().getResourceEntryName(R.mipmap.ic_status_add);
String urlPhoto = resourcePackageName + "/" + resourceTypeName + "/" + resourceEntryName;

检测手机是否安装微信、QQ、支付宝、微博

public class JudgeApplicationIsExistUtils {
    /**
     * 判断微信 方式一
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 判断微信 方式二  兼容三星S7
     */
     private static IWXAPI api; // 相应的包,请集成SDK后自行引入
	 public static boolean isWeChatAppInstalled(Context context) {
        api = WXAPIFactory.createWXAPI(context, "Your WeChat AppId");
        if (api.isWXAppInstalled() && api.isWXAppSupportAPI()) {
            return true;
        } else {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equalsIgnoreCase("com.tencent.mm")) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
    
   /**
     * 检测是否安装支付宝
     *
     * @param context
     * @return
     */
    public static boolean isAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }
    
    /**
     * 判断qq是否可用
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
 
    /**
     * 判断微博
     */
    public static boolean isWeiboIAvilible(Context context) {
        PackageManager pm;
        if ((pm = context.getApplicationContext().getPackageManager()) == null) {
            return false;
        }
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            String name = info.packageName.toLowerCase(Locale.ENGLISH);
            if ("com.sina.weibo".equals(name)) {
                return true;
            }
        }
        return false;
    }
}

使用方式

 if (JudgeApplicationIsExistUtils.isQQClientAvailable(LoginActivity.this)){
//  已经安装做你要做的事情,没有则吐丝提示一下
 }else {
        Toast.makeText(LoginActivity.this,"检测到您未安装或登录QQ!",Toast.LENGTH_SHORT).show();
}

唤醒app

如唤醒失败,查看此处第8条- -~

PackageManager packageManager = getPackageManager();
Intent intent=new Intent();
//pageage Name 自己项目的包名!
intent = packageManager.getLaunchIntentForPackage("package Name");
startActivity(intent);

特殊场景:如当前手机没有我们要唤醒的app

Intent view = new Intent ("android.intent.action.VIEW",Uri.parse("下载地址"));
startActivity(viewIntent);

注意 :uri跳转时 ,action 配置 和 category 配置,一定不能缺。category 配置是固定的;如下

<category android:name="android.intent.category.DEFAULT" />

通过url 跳转对应的三方app主件(我的使用场景:webview跳转三方支付时唤起本地app)

 //loadurl :第三方传给我们的url
 Intent intent = new Intent();
 intent.setAction(Intent.ACTION_VIEW);
 intent.setData(Uri.parse(loadUrl));
 startActivity(intent);

你可能感兴趣的:(#,项目开发知识点归纳,Android进阶之路,android,常用小功能,常见小功能,功能)