Android Hands-on tutorial Tenth article imitation Tencent mobile phone assistant small rocket launch effect _android

Source: Internet
Author: User
Tags sleep stub

Before the system from the source of the toast to do a brief analysis, see blog: Click to open the link

This article gives a small case, custom toast, simulated Tencent Guardian's small rocket launch. If you want to quickly understand the code, suggest first to look at the previous introduction click to open the link

First, define a service, in this service, complete the creation of toast (small rocket layout creation), the effect of smoke is animated play, and rely on an activity. (This activity is defined as a transparent state)

The layout file defining the activity of the smoke

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= 
"http://schemas.android.com/apk" /res/android " 
 android:layout_width=" match_parent " 
 android:layout_height=" match_parent "> 
 
 < ImageView 
  android:id= "@+id/smoke_m" 
  android:layout_width= fill_parent "android:layout_height=" Wrap 
  _content " 
  android:layout_alignparentbottom=" true " 
  android:src=" @drawable/desktop_smoke_m "/> 
 
 <imageview 
  android:layout_above= "@id/smoke_m" 
  android:id= "@+id/smoke_t" 
  android:layout_width = "Wrap_content" 
  android:layout_height= "wrap_content" 
  android:src= "@drawable/desktop_smoke_t"/> 
 
</RelativeLayout> 

Add the "smoke" animation to the corresponding smokeactivity

Package com.itydl.rockets; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.os.SystemClock; 
Import android.view.animation.AlphaAnimation; 
Import android.view.animation.Animation; 
Import Android.view.animation.AnimationSet; 
Import android.view.animation.ScaleAnimation; 
 
Import Android.widget.ImageView; public class Smokeactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {//TOD 
  O auto-generated Method Stub super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.smoke); 
  Bottom smoke picture imageview iv_m = (imageview) Findviewbyid (r.id.smoke_m); 
   
   
  Smoke pillar ImageView iv_t = (imageview) Findviewbyid (r.id.smoke_t); 
  Gradient animation alphaanimation AA = new Alphaanimation (0.0f,1.0f); 
  Aa.setduration (1000); Scale animation sets anchor points. X-axis half, y-axis picture lowest end y-value max scaleanimation sa = new Scaleanimation (1.0f, 1.0f, 0.0f, 1.0f, Animation.relative_to_self, 0.5f, Anim ation. 
  Relative_to_self, 1f); Sa.setduration (1000); 
  Animation set Add animation iv_m.startanimation (AA);//give the following picture a gradient animation animationset as = new Animationset (true); 
  As.addanimation (AA); 
  As.addanimation (SA); 
   
  Set the gradient animation and proportional animation iv_t.startanimation (as) for the top picture (smoke pillar); The activity is closed in 1 seconds, just after the animation is finished and the activity is closed. 
    This is also true of the main thread animation while the child thread is also executing the time consuming operation new Thread () {public void run () {//1 seconds later closes the current Activity systemclock.sleep (1000); Runonuithread (method in the new Runnable () {//activity class @Override public void Run () {//TODO Auto-ge 
     The Nerated method stub finish ()//closes itself also belongs to the update interface operation, so it is performed on the main thread. 
     
   } 
    }); 
  }; 
   
 }.start (); 
 } 
}

Define service to customize Toast layout, add animation to rocket pictures, parameter initialization, touch events, etc.

Package com.itydl.rockets; 
Import Android.app.Service; 
Import android.content.Intent; 
Import Android.graphics.PixelFormat; 
Import android.graphics.drawable.AnimationDrawable; 
Import Android.os.Handler; 
Import Android.os.IBinder; 
Import Android.os.SystemClock; 
Import android.view.Gravity; 
Import android.view.MotionEvent; 
Import Android.view.View; 
Import Android.view.View.OnTouchListener; 
Import Android.view.WindowManager; 
 
Import Android.widget.ImageView; 
 public class Rocketservice extends Service {private windowmanager.layoutparams params; 
 Private view view; 
 
 Private WindowManager WM; 
 @Override public IBinder onbind (Intent Intent) {//TODO auto-generated the method stub return null; 
   
  @Override public void OnCreate () {wm = (WindowManager) getsystemservice (Window_service); 
   
  Initialization of params (toast parameters) Inittoastparams (); 
 Showrocket ()//Open small Rocket super.oncreate (); /** * Initialize the parameters of the toast * * private void Inittoastparams () {
  TODO auto-generated Method Stub//XXX this should is changed to use a Dialog, with a theme.toast//defined T 
 
  Hat sets up the layout params appropriately. 
  params = new Windowmanager.layoutparams (); 
  Params.height = WindowManager.LayoutParams.WRAP_CONTENT; 
   
  Params.width = WindowManager.LayoutParams.WRAP_CONTENT; Alignment top left corner params.gravity = Gravity.left | 
  Gravity.top; Params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE/* | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE * | 
  WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 
 
  Params.format = pixelformat.translucent; Params.type = windowmanager.layoutparams.type_system_alert;//Chieftain does not respond to events by nature, changing types. 
 Type_system_alert System Elastic Window params.settitle ("Toast"); private void Closerocket () {if (view!= null) {Wm.removeview (view)//Remove small rocket}} private Handler ha Ndler = new Handler () {public void Handlemessage (Android.os.Message msg) {wm.updateviewlayout (view, params);//Update small fires Arrow on screenThe location in which to refresh the location. Belongs to the update UI. 
 Execute in main thread (update toast position)}; 
  
 }; 
  private void Showrocket () {//small rocket layout view = View.inflate (Getapplicationcontext (), r.layout.rocket, NULL); 
  ImageView Iv_rocket = (imageview) View.findviewbyid (R.id.iv_rocket); 
  Get the animated background of a small rocket animationdrawable ad = (animationdrawable) iv_rocket.getbackground (); 
   
  Start small rocket animation (small rocket animation, two picture switching) Ad.start (); Add a touch event to a small rocket (give custom toast a touch event), hold down drag the small rocket to the bottom of the screen, release the Launch Rocket View.setontouchlistener (new Ontouchlistener () {private float start 
   X 
 
   private float Starty; @Override public boolean Ontouch (View V, motionevent event) {System.out.println (Event.getx () + ":" + Event.getra 
    WX ()); 
     Drag the toast switch (event.getaction ()) {case motionevent.action_down://Press StartX = EVENT.GETRAWX (); 
     Starty = Event.getrawy (); 
    Break  Case motionevent.action_move://Press Move, drag//new x y coordinate float MoveX = EVENT.GETRAWX ()//move x coordinate float Movey = Event.getrawy ()//move y-coordinate//dx x directionPosition change value dy y direction change values float dx = movex-startx; 
     float dy = movey-starty; 
     Change the coordinates of the toast params.x + = dx; 
     Params.y + dy; 
     Re-acquire the new x y coordinate startx = MoveX; 
      
     Starty = Movey; 
     Update Toast Position wm.updateviewlayout (view, params); 
    Break Case motionevent.action_up://release, next to launch a small rocket//Judge position launch//x axis direction from the two sides of the box more than the 100,y axis direction than 200 can launch rockets if (params.x ; && params.x + view.getwidth () < Wm.getdefaultdisplay () getwidth ()-&& params.y > 200 ) {///Launch Rocket//1, rocket up/down/rocket on center line (custom toast left upper corner as datum) params.x = (Wm.getdefaultdisplay (). GetWidth ()-V 
       
      Iew.getwidth ())/2; New Thread () {//Launch rocket change Y axis is time-consuming operation, update rocket position is update UI operation public void Run () {for (int j = 0; J < View.getheight (); 
         ) {Systemclock.sleep (50);/Hibernate 50 milliseconds params.y = j; 
         J + + 5; 
Handler.obtainmessage (). Sendtotarget ()//parameter Y values change once, send a message notification update UI, update the location of the toast         
        , launch finished, close the small Rocket stopself ()//Shut down the service and close the current own service. This approach is used to close your own service. 
      Triggering the OnDestroy method, which triggers this method inside the closing small rocket}; 
       
      }.start (); 2, the effect of smoke. The effect of the smoke is also played at the same time as the rocket is running on the sub thread because the update rockets are running up and down (the child thread does not affect the main thread execution). Two threads can be simultaneous)//Smoke effect, is an animation, completed in activity, this activity needs to be defined as transparent Intent Intent = new Intent (ROCKETSERVICE.THIS,SMOKEAC 
      Tivity.class); To open an activity in a service, you need to set up the task stack: intent.addflags (intent.flag_activity_new_task);//Task Stack startactivity (intent);//Start smoke A 
    Ctivity}//Smoking activity default:break; 
   Return false;//the default returned value. 
   
  } 
  }); Wm.addview (view, params); Add a small rocket to the form manager} @Override public void OnDestroy () {//TODO auto-generated method 
 Stub closerocket ();//Close small rocket Super.ondestroy (); 
 } 
 
}

For the active person task just add a button, open the service on the line.

Package com.itydl.rockets; 
 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.view.View; 
 
public class Mainactivity extends activity { 
 
 @Override 
 protected void onCreate (Bundle savedinstancestate) { 
  super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.activity_main); 
   
 } 
 
 /** 
  * By clicking on the button to open the small rocket 
  * @param v 
 /public void Openrocket (View v) { 
  //rocketservice service = new Rocketservice (); 
  Intent service = new Intent (this,rocketservice.class); 
  StartService (Service)/Start small rocket services 
  finish ();//close the current interface. Because to show the rocket launch, you can't show in this activity 
 } 
 
} 

The final manifest file is configured with two activities and one service, as well as a pop-up form permission

<activity 
   android:name= "com.itheima62.rockets.MainActivity" 
   android:label= "@string/app_name" > 
   <intent-filter> 
    <action android:name= "Android.intent.action.MAIN"/> 
 
    <category Android:name= "Android.intent.category.LAUNCHER"/> 
   </intent-filter> 
  </activity> 
  < !--Configure the theme for this activity, transparent, untitled, Full-screen--> 
  <activity android:name= "Com.itheima62.rockets.SmokeActivity android:theme=" @android: Style/theme.translucent.notitlebar.fullscreen "></activity> 
  <service android:name=" Com.itheima62.rockets.RocketService "></service> 

Copy Code code as follows:
<uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/>

All right, the main code and features are introduced, look at the results of the operation screenshot:

Full code please see the text link at the end of the article.

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.

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.