Android Imitation 360 accelerator ball realizes memory release _android

Source: Internet
Author: User

Now the mobile phone on the suspension window applications more and more, for users, the most common suspension window application is the security software of the suspension of small control, take 360 guards, when the suspension window, it is a ball, the ball can be dragged, when the click of small ball appear large form control, you can do further operations such as: release of mobile phone memory and so on. So through the video of Mu-net, imitating the realization of the 360 accelerated ball, increased the click of the ball to release the memory function.

Because the phone is only frequency screen screenshot: After the implementation of the following figure: Click on the Open button, the suspension of the small ball control shows the percentage of memory available on the phone; when the ball is dragged, the small ball becomes the Android icon; loosen the ball and the ball is attached to the sides of the frequency screen. Click on the inside of the ball, the release of cell phone memory, click on the other area of the phone screen, the big form disappears, the ball appears again.

The effect is as follows:

The next step is to achieve some important steps:

Implementation of 1.FloatCircleView (custom view)

The process of implementing Floatcircleview is the process of customizing the view. 1, Custom View property 2, in the view's construction method to get our custom attribute 3, rewrite onmesure 4, rewrite OnDraw. We didn't customize other properties so we saved a lot of steps.

The initialization of various variables, setting the icon to display when dragging the ball, has calculated various memory. (For display on a small ball)

 public int width=100;
  public int heigth=100; Private Paint circlepaint;//Draw round private Paint textpaint; Reprint private float Availmemory; Used memory private float totalmemory;  Total memory private String text; The percentage of used memory shown is private Boolean isdraging=false;
  Whether the state is being dragged.
  Private Bitmap src; Private Bitmap Scaledbitmap;
 The scaled picture.
   /** * Initializes the brush and calculates the available memory, total memory, and percent of available memory.
    */public void initpatints () {circlepaint = new Paint ();
    Circlepaint.setcolor (Color.cyan);
    Circlepaint.setantialias (TRUE);
    Textpaint = new Paint ();
    Textpaint.setcolor (Color.White);
    Textpaint.settextsize (25);
    Textpaint.setfakeboldtext (TRUE);
    Textpaint.setantialias (TRUE);
    Set Picture src = Bitmapfactory.decoderesource (getresources (), r.mipmap.ic_launcher); The scaled picture (sets the icon to the size of a suspended ball).
    ) Scaledbitmap = Bitmap.createscaledbitmap (src, width, heigth, true);
    Calculates the used memory, total memory, percent of memory used, availmemory= (float) getavailmemory (GetContext ()); totalmemory= (float) gettotalmemory (GetcontexT ());
  text= (int) ((availmemory/totalmemory) *100) + "%";
 }

Onmeasure () is the fixed width high written dead, through the setmeasureddimension (width, heigth);
OnDraw (), for the suspension of the ball drawing. Define a Boolean variable to determine whether the current state is dragging a small ball State, if you drag a small ball State, you draw the Android icon in that position, if not the drag state, the ball is drawn. It is not difficult to draw a small ball, the key is reprint. The following 2 graphs can deepen the understanding of reprint.

1. The x-coordinate of the reprint (1.textpaint.measuretext (text); The width of the word is 2. The width of the ball/2-the width of the word/2. )
2. Y-coordinate at reprint (1. Paint.fontmetrics FontMetrics = Textpaint.getfontmetrics (), get the font attribute measurement class. 2. (fontmetrics.ascent + fontmetrics.descent)/2 Gets the height of the word. 3. Height of the ball/2-the height of the font/2)

It's a good idea to draw a picture:

/**
   * Draw small balls and text. If the small ball is in the drag state shows the Android icon, if not the drag state shows the ball.
   * @param canvas */
  @Override
  protected void OnDraw (canvas canvas) {
    if (isdraging) {
      Canvas.drawbitmap (Scaledbitmap,0,0,null);
    } else {
      //1. Draw round
      canvas.drawcircle (WIDTH/2, HEIGTH/2, WIDTH/2, circlepaint);
      2. Draw text
      Float textwidth = textpaint.measuretext (text);//Text width
      float x = width/2-TEXTWIDTH/2;
      Paint.fontmetrics FontMetrics = Textpaint.getfontmetrics ();

      float dy =-(fontmetrics.ascent + fontmetrics.descent)/2;
      Float y = heigth/2 + dy;
      Canvas.drawtext (text, x, y, textpaint);
    }



  

How to get the memory and total memory of mobile phone:

Public long Getavailmemory {//Get Android Current available memory size activitymanager am = (activitymanager) conte
    Xt.getsystemservice (Context.activity_service);
    Activitymanager.memoryinfo mi = new Activitymanager.memoryinfo ();
    Am.getmemoryinfo (MI); Mi.availmem;
  The available memory for the current system is//return formatter.formatfilesize (context, mi.availmem);//The Acquired memory size is normalized to return mi.availmem/(1024*1024);
    Public long Gettotalmemory {string str1 = "/proc/meminfo";//system memory information file string str2;
    String[] arrayofstring;
    Long initial_memory = 0;
      try {filereader localfilereader = new FileReader (STR1);
      BufferedReader localbufferedreader = new BufferedReader (Localfilereader, 8192);
      STR2 = Localbufferedreader.readline ()//Read Meminfo first row, system total memory size arrayofstring = Str2.split ("\\s+");
      for (String num:arrayofstring) {log.i (str2, num + "\ t"); } initial_memory = Integer.valueof (arrayofstring[1]). intValue () * 1024;//gets the total system memory, in KB, multiplied by 1024 into byte localbufferedreader.close ();

    catch (IOException e) {}//return formatter.formatfilesize (context, initial_memory);//byte conversion to KB or MB, memory size normalized
  Return initial_memory/(1024*1024);

 }

2. Create WindowManager Form Management class, manage the suspension ball and the bottom large form.

WindowManager class. Used to manage the display and concealment of large forms at the bottom of the entire suspension ball and mobile phone.

<uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/> permissions must be added to the manifest file.

Get form Management class by WindowManager WM = (WindowManager) getsystemservice (Context.window_service);

Using Wm.addview (view, params), add view to the form.

Use Wm.remove (view,params) To remove view from the form.

Use Wm.updateviewlayout (view,params) to update view.

Windowmanager.layoutparams is used to set various properties of a view.

1. Create a Floatviewmanager instance.

Single-case mode creates public
 static Floatviewmanager getinstance (context context) {
    if (instance==null) {
      synchronized (Floatviewmanager.class) {
        if (instance==null) {
          instance=new Floatviewmanager (context);
    }}} return inStance;
  }

2. Show the suspension ball and show the bottom form method. (The method of displaying the form is similar to the display of a suspended ball.) )

/**
   * Display floating window/public
  void Showfloatcircleview () {
  //parameter setting
    if (params==null) {
      params = new Windowmanager.layoutparams ();
      Wide and high
      params.width=circleview.width;
      Params.height=circleview.heigth;
      Alignment
      params.gravity= gravity.top| Gravity.left;
      Offset
      params.x=0;
      params.y=0;
      Type
      params.type=windowmanager.layoutparams.type_toast;
      Set the Window property.
      params.flags= windowmanager.layoutparams.flag_not_focusable| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
      Pixel format
      params.format= pixelformat.rgba_8888
    }
    Join the ball into the form.
    Wm.addview (Circleview, params);
  }

 public void Showfloatcircleview () {
 ...
 }

3. When starting the program, first create a suspension ball, the ball can be dragged, click the ball, mobile phone bottom form display (Floatmenuview), small ball hidden. Therefore, the ball (Circleview) to be setontouchlistener and Setonclicklistener event monitoring.

Analyze the event distribution of the ball; For small balls:

When Action_down, record the downx,downy of the ball, and Startx,starty,

When Action_move, drag the Circleview state to true, record the movex,movey of the ball, calculate the distance of the ball movement (Dx,dy), and then according to Wm.updateviewlayout (Circleview, params); Update the position of the ball. Finally, the coordinates of the last move are assigned to Startx,starty.

When Action_up, will circleview whether drag and drop to false, record the coordinates when lifting, UPX, according to UPX and mobile phone screen width/2, to feel the final ball is affixed to the left side of the screen, or to the right. The error of dragging the ball behind. When the ball is dragged less than 10 pixels away, it can trigger the Click event of the ball. (The touch event of the ball takes precedence over the Click event of the ball, and when the touch event returns True, the event is consumed and the event is no longer passed down.) When the touch event returns false, the event continues to pass down, triggering a click event for the ball. )

Small Ball Click event: Click on small ball, suspended ball hidden, mobile phone bottom form appears. and set the transition animation when the bottom form appears.

Set touch monitoring for Circleview. Private View.ontouchlistener circleviewontouchlistener=new View.ontouchlistener () {@Override public boolean Ontou CH (View V, motionevent event) {switch (event.getaction ()) {case Motionevent.action_down://Last pressed coordinates
          , according to Action_move understanding.
          StartX = Event.getrawx ();
          Starty = Event.getrawy ();
          The coordinates when pressed.
          Downx = Event.getrawx ();
          DownY = Event.getrawy ();
        Break
           Case MotionEvent.ACTION_MOVE:circleView.setDrageState (TRUE);
           MoveX = Event.getrawx ();
          Movey=event.getrawy ();
          float dx = movex-startx;
          float Dy=movey-starty;
          PARAMS.X+=DX;
          Params.y+=dy;
          Wm.updateviewlayout (Circleview,params);
          Startx= MoveX;
          Starty=movey;
        Break
          Case MotionEvent.ACTION_UP:float upx=event.getrawx (); if (Upx>getscreenwidth ()/2) {Params.x=getscreenwidtH ()-circleview.width;
          }else {params.x=0;
          } circleview.setdragestate (FALSE);
          Wm.updateviewlayout (Circleview,params);
          if (Math.Abs (MOVEX-DOWNX) >10) {return true;
          }else {return false;
      } Default:break;
    return false;
}
  };
    Circleview.setontouchlistener (Circleviewontouchlistener); Circleview.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {//t
        Oast.maketext (, "onclick", Toast.length_short). Show ();
        Hidden Circleview, displays the menu bar.
        Wm.removeview (Circleview);
        Showfloatmenuview ();
      Floatmenuview.startanimation ();
 }
    });

3.MyProgreeView (The realization of the small ball in the bottom form of mobile phone).

1. Initialize the brush and listen for the view gesture. Listens for click and double-click Events. (You must set the view to be clickable)

private void Initpaint () {//Draw circle Brush circlepaint = new Paint ();
    Circlepaint.setcolor (Color.argb (0xFF, 0x3a, 0x8c, 0x6c));
    Circlepaint.setantialias (TRUE);
    Draw progress bar Brush progersspaint = new Paint ();
    Progersspaint.setantialias (TRUE);
    Progersspaint.setcolor (Color.argb (0xFF, 0x4e, 0XCC, 0x66)); Progersspaint.setxfermode (New Porterduffxfermode (PorterDuff.Mode.SRC_IN))//Draw overlapping part/Draw progress Brush Textpaint = new Paint ()
    ;
    Textpaint.setantialias (TRUE);
    Textpaint.setcolor (Color.White);

    Textpaint.settextsize (25);
    Canvas bitmap = Bitmap.createbitmap (width, heigth, Bitmap.Config.ARGB_8888);
    Bitmapcanvas = new Canvas (bitmap);
    Gesture monitoring.
    Gesturedetector = new Gesturedetector (new Mygerturedetectorlistener ());
        Setontouchlistener (New Ontouchlistener () {@Override public boolean ontouch (View V, motionevent event) {
      Return Gesturedetector.ontouchevent (event);
    }
    });
    Set view can be clicked.
  Setclickable (TRUE); } classMygerturedetectorlistener extends gesturedetector.simpleongesturelistener{@Override public boolean Ondoubletap (Mo
    Tionevent e) {...//double-click the logical return SUPER.ONDOUBLETAP of the event (e); @Override public boolean onsingletapconfirmed (Motionevent e) {...//click the logical Return of the event super.ons
    Ingletapconfirmed (e);

 }
  }

2. Click and double-click an event's status update with handler interaction. When clicked, the Bezier curve is used to achieve ripple ripple effect. When you double-click, the ripple continues to drop, memory is released, and finally the percentage of memory freed after memory is displayed. Handler sends a periodic message, allowing the click of the event and the small ball of the double-click event to be redrawn continuously. (Redraw the next section).

Click the event send cycle handler. 
  private void Startsingletapanimation () {handler.postdelayed (singletaprunnable,200);
  Private singletaprunnable singletaprunnable=new singletaprunnable ();
      Class Singletaprunnable implements runnable{@Override public void Run () {count--;
        if (count>=0) {invalidate ();//Redraw continuously.
      Handler.postdelayed (singletaprunnable,200);
        }else {handler.removecallbacks (singletaprunnable);
      count=50;
  Double-click the event send cycle handler.
  private void Startdoubletapanimation () {handler.postdelayed (runnbale,50);

  Private doubletaprunnable runnbale=new doubletaprunnable ();
      Class Doubletaprunnable implements runnable{@Override public void Run () {num--;
        if (num>=0) {invalidate ();//Redraw continuously.
      Handler.postdelayed (runnbale,50);
        }else {handler.removecallbacks (Runnbale);
       Free memory.
       KillProcess ();
        Calculates the percentage of used memory after the release. num= (int) ((FloaT) Currentprogress/max) *100);

 }
    }
  }

3. Click the event and double-click the redraw of the event.

The first is the drawing of the ball, and the plotting of the ripple path.
//Draw ball
    bitmapcanvas.drawcircle (WIDTH/2, HEIGTH/2, WIDTH/2, circlepaint);
    Draws a ripple path according to path. The last path,reset before each drawing.
    Path.reset ();
    Float y = (n/A (float) num/100) *heigth;
    Path.moveto (width, y);
    Path.lineto (width, heigth);
    Path.lineto (0, heigth);
    Path.lineto (0, y);

The wavy path is then drawn using a Bezier curve.

android-Bezier Curve

The application of Bezier curve in Android

Here is a detailed explanation of the Bezier curve. In fact, there is no need for in-depth understanding. As long as you know it can be used to achieve water ripple effect on the line (Bezier curve useful, the effect can also use it to achieve. ) mainly utilizes path.rquadto (X1,Y1,X2,Y2); Endpoint (X2,y2), the Bezier curve of the auxiliary Control Point (x1,y1). Therefore, by constantly changing the position of Y1, we can draw the effect of the ripple of the effluent.

First, determine if it is a double-click event:

Double-click: Set a variable d, by changing the value of D (d of the value of the change caused by NUM, and NUM is handler in decreasing. num–;) to draw a Bezier curve. To achieve the drop effect of water ripple.

If you click: Set a Count value by changing the count value (the change of the count value is implemented in handler). count–), first determines whether the count can be divisible by 2, alternately drawing the two Bezier curves. (These two Bezier curves are just the opposite) to achieve the ripple effect.
(A For loop is the wave number of the water waves, a pair of path.rquadto (); Only one ripple is achieved. You can verify it yourself.)

 if (!issingletap) {
    float d= (n (float) num/(100/2)) *10;
      for (int i=0;i<3;i++) {
      path.rquadto (10,-d,20,0);
      Path.rquadto (10,d,20,0);
       }
    else {
      float d= (float) count/50*10;
      if (count%2==0) {for
        (int i=0;i<=3;i++) {
          path.rquadto (10,-d,30,0);
          Path.rquadto (10,d,30,0);
        }
      else {for
        (int i=0;i<=3;i++) {
          path.rquadto (10,d,30,0);
          Path.rquadto (10,-d,30,0);}}
    

Finally, the way to free memory. Remember to add <uses-permission android:name= "Android.permission.KILL_BACKGROUND_PROCESSES"/> permissions to the manifest file.

public void KillProcess () {
    Activitymanager activitymanger= (Activitymanager) GetContext (). Getsystemservice ( Context.activity_service);
    List<activitymanager.runningappprocessinfo> list=activitymanger.getrunningappprocesses ();
    if (list!=null) for
      (int i=0;i<list.size (); i++)
      {
        Activitymanager.runningappprocessinfo apinfo= List.get (i);
        String[] pkglist=apinfo.pkglist;
 if (Apinfo.importance>activitymanager.runningappprocessinfo.importance_service)
        {
          // Process.killprocess (apinfo.pid);
          for (int j=0;j<pkglist.length;j++) {
            boolean flag=pkglist[j].contains ("com.example.yyh.animation360"); This will determine whether it is the current application or it may end the current application.
            if (!flag) {
            activitymanger.killbackgroundprocesses (pkglist[j]);
          }
        }}
      

4.FloatMenuView implementation.

1. Create a float_menuview.xml, which includes a imageview+textview+ custom Myprogreeview. The
bottom form is set to be clicked. Android:clickable= ' true ';

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:orientation=" "Vertical" android:layout_width= "match_parent" android:layout_height= "Match_parent" a ndroid:background= "#33000000" > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:orientation= "vertical" android:background= "#F02F3942" android:layout_alignparentbottom= "True" android:id= "@+id/ll" android:clickable= "true" > <linearlayout android:layout_width= "Mat" Ch_parent "android:layout_height=" wrap_content "android:orientation=" Horizontal "> <imagevie
        W android:layout_width= "50DP" android:layout_height= "50DP" android:src= "@mipmap/ic_launcher"
        android:layout_gravity= "center_vertical"/> <textview android:layout_width= "Wrap_content" Android:layout_height= "WRap_content "android:textsize=" 15sp "android:textcolor=" #c93944 "android:text=" 360 Accelerator Ball "and roid:layout_gravity= "center_vertical"/> </LinearLayout> <com.example.yyh.animation360.view.my Progreeview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_grav
 Ity= "Center_horizontal" android:layout_margintop= "10DP"/> </LinearLayout> </RelativeLayout>

2. Will floatmenuview according to the condition, uses (Wm.addview (view, params), adds the view to the form.

Use Wm.remove (view,params) To remove view from the form. method to display and hide the bottom form view
The Translateanimation class is used to set the animation effect when the bottom form enters. translateanimation (int fromxtype,float fromxvalue,int toxtype,float toxvalue,int fromytype,float fromYValue,int Toytype,float toyvalue)
The reference value for the start of the int fromxtype:x axis direction has 3 options. (1. Animation.absolute: The exact coordinate value, which refers to the absolute screen pixel unit.

2.animation.relative_to_self: relative to its own coordinate value. 3.animation.relative_to_parent: The coordinate value relative to the parent container. )
Float Fromxvalue The second parameter is the starting value of the first parameter type (for example, if the first parameter is set to Animation.relative_to_self and the second parameter is 0.1f, it means to multiply the coordinate value by 0.1);

The reference value for the end point of the int toxtype:x axis direction has 3 options with the first parameter.

Float Tovalue: The fourth parameter is the starting value of the third parameter type.

The y-axis parameter is the same. Start + end point (the first parameter of each argument is the starting value of the previous argument.) )

and set the Ontouchlistener,ontouch event for this view to finally return false, indicating that this event still needs to be passed down. In order to achieve the click of other areas of the mobile phone, the bottom of the mobile phone hidden, suspended small ball display, click on the bottom form no change, click on the bottom of the form of the ball, triggering its click and double-click Events.

 View View =view.inflate (GetContext (), r.layout.float_menuview,null);
    LinearLayout linearlayout= (linearlayout) View.findviewbyid (R.ID.LL);
    Translateanimation = new Translateanimation (animation.relative_to_self,0,animation.relative_to_self,0, animation.relative_to_self,1.0f,animation.relative_to_self,0);
    Translateanimation.setduration ();
    Translateanimation.setfillafter (true);
    Linearlayout.setanimation (translateanimation);
    View.setontouchlistener (New Ontouchlistener () {
      @Override public
      boolean Ontouch (View V, motionevent event) { C9/>floatviewmanager manager=floatviewmanager.getinstance (GetContext ());
        Manager.hidefloatmenuview ();
        Manager.showfloatcircleview ();
        return false;
      }
    });
    AddView (view);

5.MyFloatService

Used to create Floatviewmanager, manage the creation and removal of the bottom form of the suspension ball + mobile phone.

public class Myfloatservice extends Service {
  @Nullable
  @Override public
  ibinder onbind (Intent Intent) { return
    null;
  }
  @Override public
  void OnCreate () {
    //To open Floatviewmanager
    floatviewmanager manager= Floatviewmanager.getinstance (this);
    Manager.showfloatcircleview ();
    Super.oncreate ();
  }



Implementation of 6.MainActivity

Define a intent, open the service (create a WindowManager single object in the service, and manage the floating ball and the bottom form of the phone.) ) to close the current activity.

public class Mainactivity extends Appcompatactivity {
  @Override
  protected void OnCreate (Bundle Savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  }
  public void StartService (view view) {
    Intent intent=new Intent (this, myfloatservice.class);
    StartService (intent);
    Finish ();
  }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.