溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Android應用中添加一個桌面未讀角標功能

發(fā)布時間:2020-12-02 16:59:46 來源:億速云 閱讀:256 作者:Leah 欄目:移動開發(fā)

這期內(nèi)容當中小編將會給大家?guī)碛嘘P如何在Android應用中添加一個桌面未讀角標功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

1.原生系統(tǒng)(原生的Launcher ),只能修改快捷方式,增加和刪除都會有toast提示

2.小米 三星  索尼 手機: 自定義的launcher:  發(fā)送顯示未讀消息數(shù)的action已經(jīng)不同了。具體可以去看代碼。。。

判斷手機的代碼:

/***
     * 在應用圖標的快捷方式上加數(shù)字
     * @param clazz 啟動的activity
     * @param isShowNum 是否顯示數(shù)字
     * @param num 顯示的數(shù)字:整型
     * @param isStroke 是否加上邊框
     * 
     */
    public static void addNumShortCut(Context context,Class<&#63;> clazz,boolean isShowNum, String num, boolean isStroke)
     {
         Log.e(TAG, "manufacturer="+Build.MANUFACTURER);
      if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")){
          //小米
       xiaoMiShortCut(context, clazz, num);

      }else if(Build.MANUFACTURER.equalsIgnoreCase("samsung")){
          //三星
          samsungShortCut(context, num);

      }else {//其他原生系統(tǒng)手機
          installRawShortCut(context, MainActivity.class, isShowNum, num, isStroke);
      }

     }

下面寫好的工具類,上面的方法也在其中。

/***
* 應用的快捷方式工具類
* 
* @author yang
* 
*/
public class AppShortCutUtil {

    private static final String TAG = "AppShortCutUtil";

    //默認圓角半徑
    private static final int DEFAULT_CORNER_RADIUS_DIP = 8;
    //默認邊框寬度
    private static final int DEFAULT_STROKE_WIDTH_DIP = 2;
    //邊框的顏色
    private static final int DEFAULT_STROKE_COLOR = Color.WHITE;
    //中間數(shù)字的顏色
    private static final int DEFAULT_NUM_COLOR = Color.parseColor("#CCFF0000");

    /***
     * 
     * 生成有數(shù)字的圖片(沒有邊框)
     * @param context
     * @param icon 圖片
     * @param isShowNum 是否要繪制數(shù)字
     * @param num 數(shù)字字符串:整型數(shù)字 超過99,顯示為"99+"
     * @return
     */
    public static Bitmap generatorNumIcon(Context context, Bitmap icon, boolean isShowNum, String num) {

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        //基準屏幕密度
        float baseDensity = 1.5f;//240dpi
        float factor = dm.density/baseDensity;

        Log.e(TAG, "density:"+dm.density);
        Log.e(TAG, "dpi:"+dm.densityDpi);
        Log.e(TAG, "factor:"+factor);

        // 初始化畫布
        int iconSize = (int) context.getResources().getDimension(android.R.dimen.app_icon_size);
        Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize, Config.ARGB_8888);
        Canvas canvas = new Canvas(numIcon);

        // 拷貝圖片
        Paint iconPaint = new Paint();
        iconPaint.setDither(true);// 防抖動
        iconPaint.setFilterBitmap(true);// 用來對Bitmap進行濾波處理,這樣,當你選擇Drawable時,會有抗鋸齒的效果
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
        Rect dst = new Rect(0, 0, iconSize, iconSize);
        canvas.drawBitmap(icon, src, dst, iconPaint);

        if(isShowNum){

            if(TextUtils.isEmpty(num)){
                num = "0";
            }

            if(!TextUtils.isDigitsOnly(num)){
                //非數(shù)字
                Log.e(TAG, "the num is not digit :"+ num);
                num = "0";
            }

            int numInt = Integer.valueOf(num);

            if(numInt > 99){//超過99

                num = "99+";

                // 啟用抗鋸齒和使用設備的文本字體大小
                Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
                numPaint.setColor(Color.WHITE);
                numPaint.setTextSize(20f*factor);
                numPaint.setTypeface(Typeface.DEFAULT_BOLD);
                int textWidth=(int)numPaint.measureText(num, 0, num.length());

                Log.e(TAG, "text width:"+textWidth);

                int circleCenter = (int) (15*factor);//中心坐標
                int circleRadius = (int) (13*factor);//圓的半徑

                //繪制左邊的圓形
                Paint leftCirPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                leftCirPaint.setColor(Color.RED);
                canvas.drawCircle(iconSize-circleRadius-textWidth+(10*factor), circleCenter, circleRadius, leftCirPaint);

                //繪制右邊的圓形
                Paint rightCirPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                rightCirPaint.setColor(Color.RED);
                canvas.drawCircle(iconSize-circleRadius, circleCenter, circleRadius, rightCirPaint);

                //繪制中間的距形
                Paint rectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                rectPaint.setColor(Color.RED);
                RectF oval = new RectF(iconSize-circleRadius-textWidth+(10*factor), 2*factor, iconSize-circleRadius, circleRadius*2+2*factor);
                canvas.drawRect(oval, rectPaint);

                //繪制數(shù)字
                canvas.drawText(num, (float)(iconSize-textWidth/2-(24*factor)), 23*factor,    numPaint);

            }else{//<=99

                // 啟用抗鋸齒和使用設備的文本字體大小
                Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
                numPaint.setColor(Color.WHITE);
                numPaint.setTextSize(20f*factor);
                numPaint.setTypeface(Typeface.DEFAULT_BOLD);
                int textWidth=(int)numPaint.measureText(num, 0, num.length());

                Log.e(TAG, "text width:"+textWidth);

                //繪制外面的圓形
                //Paint outCirPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                //outCirPaint.setColor(Color.WHITE);
                //canvas.drawCircle(iconSize - 15, 15, 15, outCirPaint);

                //繪制內(nèi)部的圓形
                Paint inCirPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                inCirPaint.setColor(Color.RED);
                canvas.drawCircle(iconSize-15*factor, 15*factor, 15*factor, inCirPaint);

                //繪制數(shù)字
                canvas.drawText(num, (float)(iconSize-textWidth/2-15*factor), 22*factor, numPaint);
            }
        }
        return numIcon;
    }

    /***
     * 
     * 生成有數(shù)字的圖片(沒有邊框)
     * @param context
     * @param icon 圖片
     * @param isShowNum 是否要繪制數(shù)字
     * @param num 數(shù)字字符串:整型數(shù)字 超過99,顯示為"99+"
     * @return
     */
    public static Bitmap generatorNumIcon2(Context context, Bitmap icon, boolean isShowNum, String num) {

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        //基準屏幕密度
        float baseDensity = 1.5f;//240dpi
        float factor = dm.density/baseDensity;

        Log.e(TAG, "density:"+dm.density);
        Log.e(TAG, "dpi:"+dm.densityDpi);
        Log.e(TAG, "factor:"+factor);

        // 初始化畫布
        int iconSize = (int) context.getResources().getDimension(android.R.dimen.app_icon_size);
        Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize, Config.ARGB_8888);
        Canvas canvas = new Canvas(numIcon);

        // 拷貝圖片
        Paint iconPaint = new Paint();
        iconPaint.setDither(true);// 防抖動
        iconPaint.setFilterBitmap(true);// 用來對Bitmap進行濾波處理,這樣,當你選擇Drawable時,會有抗鋸齒的效果
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
        Rect dst = new Rect(0, 0, iconSize, iconSize);
        canvas.drawBitmap(icon, src, dst, iconPaint);

        if(isShowNum){

            if(TextUtils.isEmpty(num)){
                num = "0";
            }

            if(!TextUtils.isDigitsOnly(num)){
                //非數(shù)字
                Log.e(TAG, "the num is not digit :"+ num);
                num = "0";
            }

            int numInt = Integer.valueOf(num);

            if(numInt > 99){//超過99
                num = "99+";
            }

            //啟用抗鋸齒和使用設備的文本字體大小
            //測量文本占用的寬度
            Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            numPaint.setColor(Color.WHITE);
            numPaint.setTextSize(20f*factor);
            numPaint.setTypeface(Typeface.DEFAULT_BOLD);
            int textWidth=(int)numPaint.measureText(num, 0, num.length());
            Log.e(TAG, "text width:"+textWidth);

            /**----------------------------------*
             * TODO 繪制圓角矩形背景 start
             *------------------------------------*/
            //圓角矩形背景的寬度
            int backgroundHeight = (int) (2*15*factor);
            int backgroundWidth = textWidth>backgroundHeight &#63; (int)(textWidth+10*factor) : backgroundHeight;

            canvas.save();//保存狀態(tài)

            ShapeDrawable drawable = getDefaultBackground(context);
            drawable.setIntrinsicHeight(backgroundHeight);
            drawable.setIntrinsicWidth(backgroundWidth);
            drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
            canvas.translate(iconSize-backgroundWidth, 0);
            drawable.draw(canvas);

            canvas.restore();//重置為之前保存的狀態(tài)

            /**----------------------------------*
             * TODO 繪制圓角矩形背景 end
             *------------------------------------*/

            //繪制數(shù)字
            canvas.drawText(num, (float)(iconSize-(backgroundWidth + textWidth)/2), 22*factor, numPaint);
        }
        return numIcon;
    }
    /***
     * 
     * 生成有數(shù)字的圖片(有邊框)
     * @param context
     * @param icon 圖片
     * @param isShowNum 是否要繪制數(shù)字
     * @param num 數(shù)字字符串:整型數(shù)字 超過99,顯示為"99+"
     * @return
     */
    public static Bitmap generatorNumIcon3(Context context, Bitmap icon, boolean isShowNum, String num) {

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        //基準屏幕密度
        float baseDensity = 1.5f;//240dpi
        float factor = dm.density/baseDensity;

        Log.e(TAG, "density:"+dm.density);
        Log.e(TAG, "dpi:"+dm.densityDpi);
        Log.e(TAG, "factor:"+factor);

        // 初始化畫布
        int iconSize = (int) context.getResources().getDimension(android.R.dimen.app_icon_size);
        Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize, Config.ARGB_8888);
        Canvas canvas = new Canvas(numIcon);

        // 拷貝圖片
        Paint iconPaint = new Paint();
        iconPaint.setDither(true);// 防抖動
        iconPaint.setFilterBitmap(true);// 用來對Bitmap進行濾波處理,這樣,當你選擇Drawable時,會有抗鋸齒的效果
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
        Rect dst = new Rect(0, 0, iconSize, iconSize);
        canvas.drawBitmap(icon, src, dst, iconPaint);

        if(isShowNum){

            if(TextUtils.isEmpty(num)){
                num = "0";
            }

            if(!TextUtils.isDigitsOnly(num)){
                //非數(shù)字
                Log.e(TAG, "the num is not digit :"+ num);
                num = "0";
            }

            int numInt = Integer.valueOf(num);

            if(numInt > 99){//超過99
                num = "99+";
            }

            //啟用抗鋸齒和使用設備的文本字體大小
            //測量文本占用的寬度
            Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            numPaint.setColor(Color.WHITE);
            numPaint.setTextSize(20f*factor);
            numPaint.setTypeface(Typeface.DEFAULT_BOLD);
            int textWidth=(int)numPaint.measureText(num, 0, num.length());
            Log.e(TAG, "text width:"+textWidth);

            /**----------------------------------*
             * TODO 繪制圓角矩形背景:先畫邊框,再畫內(nèi)部的圓角矩形 start
             *------------------------------------*/
            //圓角矩形背景的寬度
            int backgroundHeight = (int) (2*15*factor);
            int backgroundWidth = textWidth>backgroundHeight &#63; (int)(textWidth+10*factor) : backgroundHeight;
            //邊框的寬度
            int strokeThickness = (int) (2*factor);

            canvas.save();//保存狀態(tài)

            int strokeHeight = backgroundHeight + strokeThickness*2;
            int strokeWidth = textWidth>strokeHeight &#63; (int)(textWidth+ 10*factor + 2*strokeThickness) : strokeHeight;
            ShapeDrawable outStroke = getDefaultStrokeDrawable(context);
            outStroke.setIntrinsicHeight(strokeHeight);
            outStroke.setIntrinsicWidth(strokeWidth);
            outStroke.setBounds(0, 0, strokeWidth, strokeHeight);
            canvas.translate(iconSize-strokeWidth-strokeThickness, strokeThickness);
            outStroke.draw(canvas);

            canvas.restore();//重置為之前保存的狀態(tài)

            canvas.save();//保存狀態(tài)

            ShapeDrawable drawable = getDefaultBackground(context);
            drawable.setIntrinsicHeight((int) (backgroundHeight+2*factor));
            drawable.setIntrinsicWidth((int) (backgroundWidth+2*factor));
            drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
            canvas.translate(iconSize-backgroundWidth-2*strokeThickness, 2*strokeThickness);
            drawable.draw(canvas);

            canvas.restore();//重置為之前保存的狀態(tài)

            /**----------------------------------*
             * TODO 繪制圓角矩形背景 end
             *------------------------------------*/

            //繪制數(shù)字
            canvas.drawText(num, (float)(iconSize-(backgroundWidth + textWidth+4*strokeThickness)/2), (22)*factor+2*strokeThickness, numPaint);
        }
        return numIcon;
    }

    /***
     * 
     * 生成有數(shù)字的圖片(有邊框的)
     * @param context
     * @param icon 圖片
     * @param isShowNum 是否要繪制數(shù)字
     * @param num 數(shù)字字符串:整型數(shù)字 超過99,顯示為"99+"
     * @return
     */
    public static Bitmap generatorNumIcon4(Context context, Bitmap icon, boolean isShowNum, String num) {

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        //基準屏幕密度
        float baseDensity = 1.5f;//240dpi
        float factor = dm.density/baseDensity;

        Log.e(TAG, "density:"+dm.density);
        Log.e(TAG, "dpi:"+dm.densityDpi);
        Log.e(TAG, "factor:"+factor);

        // 初始化畫布
        int iconSize = (int) context.getResources().getDimension(android.R.dimen.app_icon_size);
        Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize, Config.ARGB_8888);
        Canvas canvas = new Canvas(numIcon);

        // 拷貝圖片
        Paint iconPaint = new Paint();
        iconPaint.setDither(true);// 防抖處理
        iconPaint.setFilterBitmap(true);// 用來對Bitmap進行濾波處理,這樣,當你選擇Drawable時,會有抗鋸齒的效果
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
        Rect dst = new Rect(0, 0, iconSize, iconSize);
        canvas.drawBitmap(icon, src, dst, iconPaint);

        if(isShowNum){

            if(TextUtils.isEmpty(num)){
                num = "0";
            }

            if(!TextUtils.isDigitsOnly(num)){
                //非數(shù)字
                Log.e(TAG, "the num is not digit :"+ num);
                num = "0";
            }

            int numInt = Integer.valueOf(num);

            if(numInt > 99){//超過99
                num = "99+";
            }

            //啟用抗鋸齒和使用設備的文本字體
            //測量文本占用的寬度
            Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            numPaint.setColor(Color.WHITE);
            numPaint.setTextSize(25f*factor);
            numPaint.setTypeface(Typeface.DEFAULT_BOLD);
            int textWidth=(int)numPaint.measureText(num, 0, num.length());
            Log.e(TAG, "text width:"+textWidth);

            /**----------------------------------*
             * TODO 繪制圓角矩形背景 start
             *------------------------------------*/
            //邊框的寬度
            int strokeThickness = (int) (DEFAULT_STROKE_WIDTH_DIP*factor);
            //圓角矩形背景的寬度
            float radiusPx = 15*factor;
            int backgroundHeight = (int) (2*(radiusPx+strokeThickness));//2*(半徑+邊框寬度)
            int backgroundWidth = textWidth>backgroundHeight &#63; (int)(textWidth + 10*factor + 2*strokeThickness) : backgroundHeight;

            canvas.save();//保存狀態(tài)

            ShapeDrawable drawable = getDefaultBackground2(context);
            drawable.setIntrinsicHeight(backgroundHeight);
            drawable.setIntrinsicWidth(backgroundWidth);
            drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
            canvas.translate(iconSize-backgroundWidth-strokeThickness, 2*strokeThickness);
            drawable.draw(canvas);

            canvas.restore();//重置為之前保存的狀態(tài)

            /**----------------------------------*
             * TODO 繪制圓角矩形背景 end
             *------------------------------------*/

            //繪制數(shù)字
            canvas.drawText(num, (float)(iconSize-(backgroundWidth + textWidth+2*strokeThickness)/2), (float) (25*factor+2.5*strokeThickness), numPaint);
        }
        return numIcon;
    }

    /***
     * 創(chuàng)建原生系統(tǒng)的快捷方式
     * @param context 
     * @param clazz 啟動的activity
     * @param isShowNum 是否顯示數(shù)字
     * @param num 顯示的數(shù)字:整型
     * @param isStroke 是否加上邊框
     */

    public static void installRawShortCut(Context context, Class<&#63;> clazz, boolean isShowNum, String num, boolean isStroke) {
        Log.e(TAG, "installShortCut....");

        Intent shortcutIntent = new Intent(    "com.android.launcher.action.INSTALL_SHORTCUT");
        //名稱
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,    context.getString(R.string.app_name));

        // 是否可以有多個快捷方式的副本,參數(shù)如果是true就可以生成多個快捷方式,如果是false就不會重復添加
        shortcutIntent.putExtra("duplicate", false);

        //點擊快捷方式:打開activity
        Intent mainIntent = new Intent(Intent.ACTION_MAIN);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mainIntent.setClass(context, clazz);
        shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, mainIntent);

        //快捷方式的圖標
        if(isStroke){
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON,
                    generatorNumIcon4(
                            context, 
                            ((BitmapDrawable)context.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(),
                            isShowNum, 
                            num));
        }else{
            shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON,
                    generatorNumIcon2(
                            context, 
                            ((BitmapDrawable)context.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(),
                            isShowNum, 
                            num));
        }
        context.sendBroadcast(shortcutIntent);
    }

    /***
     * 是否已經(jīng)創(chuàng)建了快捷方式
     * @param context
     * @return
     */
    public static boolean isAddShortCut(Context context) {
         Log.e(TAG, "isAddShortCut....");

      boolean isInstallShortcut = false;
      final ContentResolver cr = context.getContentResolver();

      //TODO 注釋的代碼,在有的手機:修改了ROM的系統(tǒng),不能支持
      /*int versionLevel = android.os.Build.VERSION.SDK_INT;
            String AUTHORITY = "com.android.launcher2.settings";
            //2.2以上的系統(tǒng)的文件文件名字是不一樣的
            if (versionLevel >= 8) {
              AUTHORITY = "com.android.launcher2.settings";
            } else {
              AUTHORITY = "com.android.launcher.settings";
            }*/

        String AUTHORITY = getAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS");
        Log.e(TAG, "AUTHORITY : " +AUTHORITY);
        final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
        + "/favorites&#63;notify=true");

        Cursor c = cr.query(CONTENT_URI,
            new String[] { "title" }, "title=&#63;",
            new String[] { context.getString(R.string.app_name) }, null);

        if (c != null && c.getCount() > 0) {
          isInstallShortcut = true;
        }

        if(c != null){
            c.close();
        }

        Log.e(TAG, "isAddShortCut....isInstallShortcut="+isInstallShortcut);

      return isInstallShortcut;
    }

    /**
     * 刪除快捷方式 
     * @param context
     * @param clazz
     */
     public static void deleteShortCut(Context context, Class<&#63;> clazz){
         Log.e(TAG, "delShortcut....");

         if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")){
            //小米
            //當為""時,不顯示數(shù)字,相當于隱藏了)
            xiaoMiShortCut(context, clazz, "");

        }else if(Build.MANUFACTURER.equalsIgnoreCase("samsung")){
            //三星
            samsungShortCut(context, "0");

        }else {//其他原生系統(tǒng)手機
            //刪除顯示數(shù)字的快捷方式
            deleteRawShortCut(context, clazz);
            //安裝不顯示數(shù)字的快捷方式
            //installRawShortCut(context, clazz, false, "0");
        }
     }

    /***
     * 刪除原生系統(tǒng)的快捷方式
     * @param context
     * @param clazz 啟動的activity
     */
    public static void deleteRawShortCut(Context context, Class<&#63;> clazz) {
        Intent intent = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
        //快捷方式的名稱
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));

        Intent intent2 = new Intent(); 
        intent2.setClass(context, clazz); 
        intent2.setAction(Intent.ACTION_MAIN); 
        intent2.addCategory(Intent.CATEGORY_LAUNCHER); 
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,intent2); 

        context.sendBroadcast(intent);
    }

     /***
     * 取得權限相應的認證URI
     * @param context
     * @param permission
     * @return
     */
    public static String getAuthorityFromPermission(Context context, String permission) {
        if (TextUtils.isEmpty(permission)) {
            return null;
        }
        List<PackageInfo> packInfos = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packInfos == null) {
            return null;
        }
        for (PackageInfo info : packInfos) {
            ProviderInfo[] providers = info.providers;
            if (providers != null) {
                for (ProviderInfo provider : providers) {
                    if (permission.equals(provider.readPermission)
                            || permission.equals(provider.writePermission)) {
                        return provider.authority;
                    }
                }
            }
        }
        return null;
    }

    /***
     * 在小米應用圖標的快捷方式上加數(shù)字<br>
     * 
     * 
     * @param context
     * @param num 顯示的數(shù)字:大于99,為"99",當為""時,不顯示數(shù)字,相當于隱藏了)<br><br>
     * 
     * 注意點:
     * context.getPackageName()+"/."+clazz.getSimpleName() (這個是啟動activity的路徑)中的"/."不能缺少
     * 
     */
    public static void xiaoMiShortCut(Context context,Class<&#63;> clazz, String num)
     {
        Log.e(TAG, "xiaoMiShortCut....");
        Intent localIntent = new Intent("android.intent.action.APPLICATION_MESSAGE_UPDATE");
        localIntent.putExtra("android.intent.extra.update_application_component_name", context.getPackageName()+"/."+clazz.getSimpleName());
        if(TextUtils.isEmpty(num)){
            num = "";
        }else{
          int numInt = Integer.valueOf(num);
          if (numInt > 0){
             if (numInt > 99){
                num = "99";
           }
          }else{
              num = "0";
          }
        }
        localIntent.putExtra("android.intent.extra.update_application_message_text", num);
        context.sendBroadcast(localIntent);
     }                                            

     /***
     * 索尼手機:應用圖標的快捷方式上加數(shù)字
     * @param context
     * @param num
     */
    public static void sonyShortCut(Context context, String num)
     {
      String activityName = getLaunchActivityName(context);
      if (activityName == null){
       return;
      }
      Intent localIntent = new Intent();
      int numInt = Integer.valueOf(num);
      boolean isShow = true;
      if (numInt < 1){
       num = "";
       isShow = false;
      }else if (numInt > 99){
          num = "99";
      }
      localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", isShow);
      localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
      localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", activityName);
      localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", num);
      localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());
      context.sendBroadcast(localIntent);
     }

     /***
     * 三星手機:應用圖標的快捷方式上加數(shù)字
     * @param context
     * @param num
     */
    public static void samsungShortCut(Context context, String num)
     {
        int numInt = Integer.valueOf(num);
      if (numInt < 1)
      {
       num = "0";
      }else if (numInt > 99){
          num = "99";
      }
         String activityName = getLaunchActivityName(context);
      Intent localIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
      localIntent.putExtra("badge_count", num);
      localIntent.putExtra("badge_count_package_name", context.getPackageName());
      localIntent.putExtra("badge_count_class_name", activityName);
      context.sendBroadcast(localIntent);
     }

     /***
     * 在應用圖標的快捷方式上加數(shù)字
     * @param clazz 啟動的activity
     * @param isShowNum 是否顯示數(shù)字
     * @param num 顯示的數(shù)字:整型
     * @param isStroke 是否加上邊框
     * 
     */
    public static void addNumShortCut(Context context,Class<&#63;> clazz,boolean isShowNum, String num, boolean isStroke)
     {
         Log.e(TAG, "manufacturer="+Build.MANUFACTURER);
      if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")){
          //小米
       xiaoMiShortCut(context, clazz, num);

      }else if(Build.MANUFACTURER.equalsIgnoreCase("samsung")){
          //三星
          samsungShortCut(context, num);

      }else {//其他原生系統(tǒng)手機
          installRawShortCut(context, MainActivity.class, isShowNum, num, isStroke);
      }

     }

     /***
     * 取得當前應用的啟動activity的名稱:
     * mainfest.xml中配置的 android:name:"
     * @param context
     * @return
     */
    public static String getLaunchActivityName(Context context)
     {
      PackageManager localPackageManager = context.getPackageManager();
      Intent localIntent = new Intent("android.intent.action.MAIN");
      localIntent.addCategory("android.intent.category.LAUNCHER");
      try
      {
       Iterator<ResolveInfo> localIterator = localPackageManager.queryIntentActivities(localIntent, 0).iterator();
       while (localIterator.hasNext())
       {
        ResolveInfo localResolveInfo = localIterator.next();
        if (!localResolveInfo.activityInfo.applicationInfo.packageName.equalsIgnoreCase(context.getPackageName()))
         continue;
        String str = localResolveInfo.activityInfo.name;
        return str;
       }
      }
      catch (Exception localException)
      {
       return null;
      }
      return null;
     }

    /***
     * 得到一個默認的背景:圓角矩形<br><br>
     * 使用代碼來生成一個背景:相當于用<shape>的xml的背景
     * 
     * @return
     */
    private static ShapeDrawable getDefaultBackground(Context context) {

        //這個是為了應對不同分辨率的手機,屏幕兼容性
        int r = dipToPixels(context,DEFAULT_CORNER_RADIUS_DIP);
        float[] outerR = new float[] {r, r, r, r, r, r, r, r};

        //圓角矩形
        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        ShapeDrawable drawable = new ShapeDrawable(rr);
        drawable.getPaint().setColor(DEFAULT_NUM_COLOR);//設置顏色
        return drawable;

    }
    /***
     * 得到一個默認的背景:圓角矩形<br><br>
     * 使用代碼來生成一個背景:相當于用<shape>的xml的背景
     * 
     * @return
     */
    private static ShapeDrawable getDefaultBackground2(Context context) {

        //這個是為了應對不同分辨率的手機,屏幕兼容性
        int r = dipToPixels(context,DEFAULT_CORNER_RADIUS_DIP);
        float[] outerR = new float[] {r, r, r, r, r, r, r, r};
        int distance = dipToPixels(context,DEFAULT_STROKE_WIDTH_DIP);

        //圓角矩形
        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        customBorderDrawable drawable = new customBorderDrawable(context,rr);
        drawable.getFillpaint().setColor(DEFAULT_NUM_COLOR);//設置填充顏色
        drawable.getStrokepaint().setColor(DEFAULT_STROKE_COLOR);//設置邊框顏色
        drawable.getStrokepaint().setStrokeWidth(distance);//設置邊框寬度
        return drawable;

    }

    /***
     * 得到一個默認的背景:圓角矩形<br><br>
     * 使用代碼來生成一個背景:相當于用<shape>的xml的背景
     * 
     * @return
     */
    private static ShapeDrawable getDefaultStrokeDrawable(Context context) {

        //這個是為了應對不同分辨率的手機,屏幕兼容性
        int r = dipToPixels(context, DEFAULT_CORNER_RADIUS_DIP);
        int distance = dipToPixels(context, DEFAULT_STROKE_WIDTH_DIP);
        float[] outerR = new float[] {r, r, r, r, r, r, r, r};

        //圓角矩形
        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        ShapeDrawable drawable = new ShapeDrawable(rr);
        drawable.getPaint().setStrokeWidth(distance);
        drawable.getPaint().setStyle(Paint.Style.FILL);
        drawable.getPaint().setColor(DEFAULT_STROKE_COLOR);//設置顏色
        return drawable;
    }
    /***
     * dp to px
     * @param dip
     * @return
     */
    public static int dipToPixels(Context context, int dip) {
        Resources r = context.getResources();
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
        return (int) px;
    }
}

上述就是小編為大家分享的如何在Android應用中添加一個桌面未讀角標功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI