android desktop icon to add a digital subscript


Whether to support the subscript is not related to mobile phone manufacturers, but you are currently using launcher development companies related.

Ways:

import android.app.Application;
import android.app.Notification;
import android.content.Intent;
import android.support.annotation.NonNull;

/**
 *谷歌
 */
public class GoogleModelImpl implements IconBadgeNumModel {
    private static final String NOTIFICATION_ERROR = "google not support before API O";

    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) {
            throw new Exception(NOTIFICATION_ERROR);
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", Utils.getInstance().getLaunchIntentForPackage(context)); // com.test. badge.MainActivity is your apk main activity

//        if (Utils.getInstance().canResolveBroadcast(context, intent)) {
            context.sendBroadcast(intent);
//        } else {
//            throw new Exception(UNABLE_TO_RESOLVE_INTENT_ERROR_ + intent.toString());
//        }

        return notification;
    }

}
import android.app.Application;
import android.app.Notification;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;

/**
 * https://developer.huawei.com/consumer/cn/devservice/doc/30802
 * <p>
 * 华为
 */
public class HuaWeiModelImpl implements IconBadgeNumModel {
    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        Bundle bunlde = new Bundle();
        bunlde.putString("package", context.getPackageName()); // com.test.badge is your package name
        bunlde.putString("class", Utils.getInstance().getLaunchIntentForPackage(context)); // com.test. badge.MainActivity is your apk main activity
        bunlde.putInt("badgenumber", count);
        context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bunlde);
        return notification;
    }
}
import android.app.Application;
import android.app.Notification;
import android.support.annotation.NonNull;
//魅族
public class MeizuModelImpl implements IconBadgeNumModel {
    private static final String NOTIFICATION_ERROR = "not support : meizu";

    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        if (true) {
            throw new Exception(NOTIFICATION_ERROR);
        }
        return null;
    }
}
Import android.app.Application;
 Import android.app.Notification;
 Import android.support.annotation.NonNull; 

/ ** 
 * The following is a description oppo Service (where not described in the Japanese 3.3 and total viable downloads standard) 
 * <P > 
 * pro, you can submit your application by mail, e-mail the following form: 
 * <the p-> 
 * 1. theme: "open application OPPO mobile application permissions subscript - (application name)" 
 * <the p-> 
 * 2. income people member: [email protected] 
 * <P> 
 * 3. body: the materials needed to apply the subscript 
 * the following is the standard application application angle required: 
 * 1. applicant application side basic information (name, email, phone , micro-channel); 
 * 2. apply party manufacturers description (less than 200 words); 
 * 3. within the application IOS application for nearly a month and the average daily amount of live Android and total downloads introduction; 
 * 4. application application main function introduction (less than 100 words); 
 all application scenarios * the subscript desired application appears. (Ie what kind of information needs to appear subscript, the need to list all) 
 * <the p->  
 * Once the access request subscript here in the form of messages, OPPO party auditor will be given of the reception date of 10 working days Audit results. Thank you for your attention and trust OPPO open platform, but also
 * Please be patient Oh ~ 
 * / 
public  class OPPOModelImpl implements IconBadgeNumModel {
    private static final String NOTIFICATION_ERROR = "not support : oppo";

    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        if (true) {
            throw new Exception(NOTIFICATION_ERROR);
        }
        return null;
    }
}
Import android.app.Application;
 Import android.app.Notification;
 Import android.content.Intent;
 Import android.support.annotation.NonNull; 

Import  static com.demo.badges.Utils.UNABLE_TO_RESOLVE_INTENT_ERROR_; 

/ ** 
 * did not find official documents description, only the online process 
 * <P> 
 * the Galaxy S8 / SM-G9500 / Android 8.0 
 * the Galaxy the Galaxy Note8 / SM-N9500 / Android 8.0 
 * Samsung 
 * / 
public  class SamsungModelImpl the implements IconBadgeNumModel {
     Private  static  Final String NOTIFICATION_ERROR = "Not Support : samsung " ; 

    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", Utils.getInstance().getLaunchIntentForPackage(context));

        if (Utils.getInstance().canResolveBroadcast(context, intent)) {
            context.sendBroadcast(intent);
        } else {
            throw new Exception(UNABLE_TO_RESOLVE_INTENT_ERROR_ + intent.toString());
        }
        return notification;
    }
}
Import android.app.Application;
 Import android.app.Notification;
 Import android.support.annotation.NonNull; 

/ ** 
 * this code found on the Internet, but in vivo X21A [android-8.1.0 / Funtouch OS_4.0] not tested successfully on a real machine. 
 * After contact with a live person in vivo developer platform, the other replies method has not been disclosed can be set, there is no channel can apply only vivo applications specified can be achieved (micro-channel, microblogging and other) 
 * / 
public  class VIVOModelImpl the implements {IconBadgeNumModel
     Private  static  Final String NOTIFICATION_ERROR = "Not Support: Vivo" ; 

    @Override 
    public the Notification setIconBadgeNum (@NonNull the Application context, the Notification Notification, int COUNT) throws Exception {
        if (true) {
            throw new Exception(NOTIFICATION_ERROR);
        }
        return null;
    }
}
import android.app.Application;
import android.app.Notification;
import android.support.annotation.NonNull;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * https://dev.mi.com/console/doc/detail?pId=939
 * <p>
 * 必须发送通知
 */
public class XiaoMiModelImpl implements IconBadgeNumModel {
    private static final String NOTIFICATION_ERROR = "Xiaomi phones must send notification";

    @Override
    public Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception {
        if (notification == null) {
            throw new Exception(NOTIFICATION_ERROR);
        }
        Field field = notification.getClass().getDeclaredField("extraNotification");
        Object extraNotification = field.get(notification);
        Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
        method.invoke(extraNotification, count);
        return notification;
    }
}
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;

public class Utils {
    public static final String UNABLE_TO_RESOLVE_INTENT_ERROR_ = "unable to resolve intent: ";

    private static Utils instance;

    public static Utils getInstance() {
        if (instance == null) {
            instance = new Utils();
        }
        return instance;
    }

    public boolean canResolveBroadcast(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(intent, 0);
        return receivers != null && receivers.size() > 0;
    }

    public String getLaunchIntentForPackage(Context context) {
        return context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getClassName();
    }
}
import android.app.Application;
import android.app.Notification;
import android.support.annotation.NonNull;

public interface IconBadgeNumModel {
    Notification setIconBadgeNum(@NonNull Application context, Notification notification, int count) throws Exception;
}
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;

public class LauncherHelper {
    public final static String GOOGLE = "google";
    public final static String HUAWEI = "huawei";
    public final static String MEIZU = "meizu";
    public final static String XIAOMI = "xiaomi";
    public final static String OPPO = "oppo";
    public final static String VIVO = "vivo";
    public final static String SAMSUNG = "samsung";

    private static Map<String, String> launcherMap;

    static {
        launcherMap = new HashMap<>();
        launcherMap.put("com.huawei.android.launcher", HUAWEI);
        launcherMap.put("com.miui.home", XIAOMI);
        launcherMap.put("com.sec.android.app.launcher", SAMSUNG);
        launcherMap.put("com.google.android.apps.nexuslauncher", GOOGLE);
    }

    @Nullable
    public String getLauncherTypeByName(@NonNull String launcherName) {
        return launcherMap.get(launcherName);
    }

    @Nullable
    public String getLauncherPackageName(@NonNull Context context) {
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        final ResolveInfo res = context.getPackageManager().resolveActivity(intent, 0);
        if (res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return null;
        }
        if (res.activityInfo.packageName.equals("android")) {
            return null;
        } else {
            return res.activityInfo.packageName;
        }
    }
}
import android.app.Application;
import android.app.Notification;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

public class IconBadgeNumManager implements IconBadgeNumModel {
    private static final String NOT_SUPPORT_PHONE = "not support your phone [ Build.MANUFACTURER is null ]";
    private static final String NOT_SUPPORT_MANUFACTURER_ = "not support ";
    private static final String NOT_SUPPORT_LAUNCHER = "not support your launcher [ default launcher is null ]";
    private static final String NOT_SUPPORT_LAUNCHER_ = "not support ";
    private Map<String, IconBadgeNumModel> iconBadgeNumModelMap;
    private LauncherHelper launcherHelper;

    public IconBadgeNumManager() {
        this.launcherHelper = new LauncherHelper();
        iconBadgeNumModelMap = new HashMap<>();
    }

    @Override
    publicSetIconBadgeNum the Notification (@NonNull the Application context, the Notification Notification, int COUNT) throws Exception { 
        IconBadgeNumModel iconBadgeNumModel = getSetIconBadgeNumModel (context);
         return iconBadgeNumModel.setIconBadgeNum (context, Notification, COUNT); 
    } 

    / ** 
     * to obtain the corresponding mobile phone according to the type Model 
     * 
     * @deprecated determining more accurately the current launcher
      * / 
    @Deprecated 
    @NonNull 
    Private IconBadgeNumModel getIconBadgeNumModelByManufacturer () throws Exception {
         IF (TextUtils.isEmpty(Build.MANUFACTURER)) {
            throw new Exception(NOT_SUPPORT_PHONE);
        }
        switch (Build.MANUFACTURER.toLowerCase()) {
            case MobileBrand.HUAWEI:
                return new GoogleModelImpl();
            case MobileBrand.XIAOMI:
                return new XiaoMiModelImpl();
            case MobileBrand.VIVO:
                return new VIVOModelImpl();
            case MobileBrand.OPPO:
                return new OPPOModelImpl();
            case MobileBrand.SAMSUNG:
                return new SamsungModelImpl();
            case MobileBrand.MEIZU:
                return new MeizuModelImpl();
            case MobileBrand.GOOGLE:
                return new GoogleModelImpl();
            default:
                throw new Exception(NOT_SUPPORT_MANUFACTURER_ + Build.MANUFACTURER);
        }
    }

    /**
     * 根据手机当前launcher获取相应Model
     */
    @NonNull
    private IconBadgeNumModel getIconBadgeNumModelByLauncher(@NonNull String launcherType) throws Exception {
        switch (launcherType) {
            case LauncherHelper.HUAWEI:
                return new HuaWeiModelImpl();
            case LauncherHelper.XIAOMI:
                return new XiaoMiModelImpl();
            case LauncherHelper.VIVO:
                return new VIVOModelImpl();
            case LauncherHelper.OPPO:
                return new OPPOModelImpl();
            case LauncherHelper.SAMSUNG:
                return new SamsungModelImpl();
            case LauncherHelper.MEIZU:
                return new MeizuModelImpl();
            case LauncherHelper.GOOGLE:
                return new GoogleModelImpl();
            default:
                throw new Exception(NOT_SUPPORT_LAUNCHER_ + launcherType);
        }
    }

    @NonNull
    private IconBadgeNumModel getSetIconBadgeNumModel(@NonNull Application context) throws Exception {
        String launcherName = launcherHelper.getLauncherPackageName(context);
        if (TextUtils.isEmpty(launcherName)) {
            throw new Exception(NOT_SUPPORT_LAUNCHER);
        }
        String launcherType = launcherHelper.getLauncherTypeByName(launcherName);
        if (TextUtils.isEmpty(launcherType)) {
            throw new Exception(NOT_SUPPORT_LAUNCHER_ + launcherName);
        }
        if (iconBadgeNumModelMap.containsKey(launcherType)) {
            return iconBadgeNumModelMap.get(launcherType);
        }
        IconBadgeNumModel iconBadgeNumModel = getIconBadgeNumModelByLauncher(launcherType);
        iconBadgeNumModelMap.put(launcherType, iconBadgeNumModel);
        return iconBadgeNumModel;
    }
}

test:

import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.demo.badges.LauncherHelper;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(TAG, Build.MANUFACTURER);
        Log.e(TAG, new LauncherHelper().getLauncherPackageName(this));

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, MyService.class);
                startService(i);
            }
        });
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, MyService.class);
                stopService(i);
            }
        });
    }
}
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;

import com.demo.badges.IconBadgeNumManager;

public class MyService extends Service {
    IconBadgeNumManager setIconBadgeNumManager;
    private boolean isStop;
    private int count;
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!isStop) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count += 2;
                sendIconNumNotification();
            }
        }
    });

    public MyService() {
        setIconBadgeNumManager = new IconBadgeNumManager();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isStop = false;
        thread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isStop = true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void sendIconNumNotification() {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm == null) return;
        String notificationChannelId = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = createNotificationChannel();
            nm.createNotificationChannel(notificationChannel);
            notificationChannelId = notificationChannel.getId();
        }
        Notification notification = null;
        try {
            notification = new NotificationCompat.Builder(this, notificationChannelId)
                    .setSmallIcon(getApplicationInfo().icon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle("title")
                    .setContentText("content num: " + count)
                    .setTicker("ticker")
                    .setAutoCancel(true)
                    .setNumber(count)
                    .build();
            notification = setIconBadgeNumManager.setIconBadgeNum(getApplication(), notification, count);

            nm.notify(32154, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequiresApi(api =Build.VERSION_CODES.O)
     Private  staticCreateNotificationChannel NotificationChannel () { 
        String channelId = "the Test" ; 
        NotificationChannel Channel = null ; 
        Channel = new new NotificationChannel (channelId,
                 "Channel1" , NotificationManager.IMPORTANCE_DEFAULT); 
        channel.enableLights ( to true ); // whether small icon in the upper right corner to show the desktop red dot 
        channel.setLightColor (Color.RED); // red dot color 
        channel.setShowBadge ( to true ;) // is displayed when long press the desktop icon in the notification of this channel 
        return channel; 
    } 
}

 Huawei cell phone pro-test possible!

Guess you like

Origin www.cnblogs.com/loaderman/p/11949985.html