Implementation principle of Android imitating Weibo's praise function of continues to praise and then cancels

  • 2021-08-21 21:31:16
  • OfStack

Product requirements, to achieve a continuous praise and then cancel function similar to Weibo, because I occasionally brush Weibo, and I have a certain understanding of the use of this function.

As for the specific implementation of Weibo's praise, I don't know. Weibo's praise can still be praised when the network is disconnected, and it won't prompt the network to be abnormal. After there is a network,

Refresh, in fact, there is no praise, so let's realize it according to this phenomenon.

Avoid concurrency and reduce the pressure of CPU. Personally, I will think of HandlerThread. I don't know how to popularize science by myself. Here, I only talk about the principle of praise function I realized.


private Timer mTimer;// Timer  
private TimerTask mTask; 
mMap = new HashMap<>(); 
mMainHandler = new MainHandler();// Handle main thread tasks  
mHandlerThread = new HandlerThread("praise_thread"); 
mHandlerThread.start();//start() Must be in getLooper() Pre-invocation  
mThreadHandler = new ChildThreadHandler(mHandlerThread.getLooper());// Handle sub-thread tasks  

Self-encapsulates a single-column management class:

private Map<String, Map<Long, Integer>> mMap;// Realize a like message manager based on my own needs. The first key here is the user, and the second key is the only 1ID of the content

Store the like message in the manager and join the task queue


public void addReport(String userId, long aId, int state) { 
  stopTask();// Stop timer  
  init();// Initialization operation  
  Map<Long, Integer> map; 
  if (mMap.containsKey(userId)) {// This is the processing user key 
    map = mMap.get(userId); 
  } else { 
    map = new Hashtable<>();// Avoid repetition and popularize science by yourself  
    mMap.put(userId, map); 
  } 
  if (!map.containsKey(aId)) {// If there is a description handler Queue already exists but has not been processed  
     sendMsg(mThreadHandler, 0, userId, aId, state);// Add tasks to child threads  
  } 
  map.put(aId, state);// Record the praise status of the content to be submitted  
} 

Sub-thread message processing: report the message of user operation and send the report result back to the main thread

Main thread message processing: take out the corresponding value in map and compare it with the reported result.

1. If there is uniformity, remove the corresponding key-value in map, and then cut off whether there is any message not reported in map.

Otherwise, the timer will be turned on and the thread will be terminated at a fixed time.

2. If it is not 1, send the report message to the child thread again.

Summarize


Related articles: