Android编程--常用代码

原文请参见:http://blog.csdn.net/myarrow/article/details/16981921


目录(?)[+]

1. 如何使用Handler?

创建Handler的方式:

1) new Handler() 
    创建目前正在执行此指令的线程的Handler对象,其Looper通过Looper.Looper.myLooper()获取
2) new Handler(Looper)
    创建指定Looper线程的Handler对象, 如new Handler(Looper.getMainLooper())创建主线程的Handler对象


发送Message方案一:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static final int KEEP_SCREEN_ON_MSG = 1;  
  2. static final int GET_NEW_SURFACE_MSG = 2;  
  3. static final int UPDATE_WINDOW_MSG = 3;  
  4.   
  5. final Handler mHandler = new Handler() {  
  6.     @Override  
  7.     public void handleMessage(Message msg) {  
  8.         switch (msg.what) {  
  9.             case KEEP_SCREEN_ON_MSG: {  
  10.                 setKeepScreenOn(msg.arg1 != 0);  
  11.             } break;  
  12.             case GET_NEW_SURFACE_MSG: {  
  13.                 handleGetNewSurface();  
  14.             } break;  
  15.             case UPDATE_WINDOW_MSG: {  
  16.                 updateWindow(falsefalse);  
  17.             } break;  
  18.         }  
  19.     }  
  20. };  
  21.   
  22. //发送空消息  
  23. mHandler.sendEmptyMessage(UPDATE_WINDOW_MSG);  
  24.   
  25. //发送一个Message  
  26. Message msg = mHandler.obtainMessage(GET_NEW_SURFACE_MSG);  
  27. mHandler.sendMessage(msg);  


发送Message方案二:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class AudioHandler extends Handler {  
  2.   
  3.         private void setDeviceVolume(VolumeStreamState streamState, int device) {  
  4.             //do something  
  5.         }  
  6.   
  7.         private void setAllVolumes(VolumeStreamState streamState) {  
  8.             //do something  
  9.         }  
  10.   
  11.         @Override  
  12.         public void handleMessage(Message msg) {  
  13.   
  14.             switch (msg.what) {  
  15.   
  16.                 case MSG_SET_DEVICE_VOLUME:  
  17.                     setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);  
  18.                     break;  
  19.   
  20.                 case MSG_SET_ALL_VOLUMES:  
  21.                     setAllVolumes((VolumeStreamState) msg.obj);  
  22.                     break;  
  23.                 // ...  
  24.             }  
  25.         }  
  26.     }  

发送Runnable方案三:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.     private Handler h;  
  3.       
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.main);  
  8.           
  9.         h = new Handler(){  
  10.             public void handleMessage(Message msg) {  
  11.                 //do nothing  
  12.             }  
  13.         };   
  14.           
  15.         h.post(new myRun());  
  16.     }  
  17.       
  18.     class myRun implements Runnable{  
  19.         public void run(){   
  20.             setTitle(String.valueOf(1));  
  21.             h.postDelayed(testRun, 2000);  
  22.         }  
  23.     }  
  24.   
  25.     Runnable testRun= new Runnable() {  
  26.         public void run(){  
  27.             setTitle(String.valueOf(2));  
  28.         }  
  29.     };  
  30. }  


2. 如何使用Looper

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Looper.prepare();  
  2. // 创建Handler          
  3. Looper.loop();  
  4. // 在此线程中创建的Handler将向Looper的MessageQueue发送消息  


3. 创建、实现、启动线程

方案一:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. new Thread(){  
  2.     public void run(){  
  3.          //do something you want to do  
  4.     }  
  5. }.start();  

方案二:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class Task implements Runnable {  
  2.     public void run() {  
  3.          // do something you want to do  
  4.     }  
  5. }  
  6.   
  7. Task ta = new Task();  
  8. Thread t1 = new Thread(ta, "MyTask");  
  9. t1.start();  

方案三:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class MyThread extends Thread {  
  2.     public MyThread() {  
  3.         super("MyThread");  
  4.     }  
  5.   
  6.     @Override  
  7.     public void run() {  
  8.         Looper.prepare();  
  9.         mMyLooper = Looper.myLooper();  
  10.         mAudioHandler = new AudioHandler();  
  11.         //do something you want to do    
  12.         Looper.loop();  
  13.     }  
  14. }  
  15.   
  16. AudioHandler mAudioHandler;  
  17. Looper mMyLooper;  
  18. MyThread mMyThread = new MyThread();  
  19. mMyThread.start(); //启动线程  
  20. // wait some event  
  21. mMyLooper.quit(); //使线程退出  


4. 实现SurfaceHolder

    在SurfaceView中实现的SurfaceHolder如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private SurfaceHolder mSurfaceHolder = new SurfaceHolder() {  
  2.       
  3.     private static final String LOG_TAG = "SurfaceHolder";  
  4.       
  5.     public boolean isCreating() {  
  6.         return mIsCreating;  
  7.     }  
  8.   
  9.     public void addCallback(Callback callback) {  
  10.         synchronized (mCallbacks) {  
  11.             // This is a linear search, but in practice we'll   
  12.             // have only a couple callbacks, so it doesn't matter.  
  13.             if (mCallbacks.contains(callback) == false) {        
  14.                 mCallbacks.add(callback);  
  15.             }  
  16.         }  
  17.     }  
  18.   
  19.     public void removeCallback(Callback callback) {  
  20.         synchronized (mCallbacks) {  
  21.             mCallbacks.remove(callback);  
  22.         }  
  23.     }  
  24.       
  25.     public void setFixedSize(int width, int height) {  
  26.         if (mRequestedWidth != width || mRequestedHeight != height) {  
  27.             mRequestedWidth = width;  
  28.             mRequestedHeight = height;  
  29.             requestLayout();  
  30.         }  
  31.     }  
  32.   
  33.     public void setSizeFromLayout() {  
  34.         if (mRequestedWidth != -1 || mRequestedHeight != -1) {  
  35.             mRequestedWidth = mRequestedHeight = -1;  
  36.             requestLayout();  
  37.         }  
  38.     }  
  39.   
  40.     public void setFormat(int format) {  
  41.   
  42.         // for backward compatibility reason, OPAQUE always  
  43.         // means 565 for SurfaceView  
  44.         if (format == PixelFormat.OPAQUE)  
  45.             format = PixelFormat.RGB_565;  
  46.   
  47.         mRequestedFormat = format;  
  48.         if (mWindow != null) {  
  49.             updateWindow(falsefalse);  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * @deprecated setType is now ignored. 
  55.      */  
  56.     @Deprecated  
  57.     public void setType(int type) { }  
  58.   
  59.     public void setKeepScreenOn(boolean screenOn) {  
  60.         Message msg = mHandler.obtainMessage(KEEP_SCREEN_ON_MSG);  
  61.         msg.arg1 = screenOn ? 1 : 0;  
  62.         mHandler.sendMessage(msg);  
  63.     }  
  64.       
  65.     public Canvas lockCanvas() {  
  66.         return internalLockCanvas(null);  
  67.     }  
  68.   
  69.     public Canvas lockCanvas(Rect dirty) {  
  70.         return internalLockCanvas(dirty);  
  71.     }  
  72.   
  73.     private final Canvas internalLockCanvas(Rect dirty) {  
  74.         mSurfaceLock.lock();  
  75.   
  76.         if (DEBUG) Log.i(TAG, "Locking canvas... stopped="  
  77.                 + mDrawingStopped + ", win=" + mWindow);  
  78.   
  79.         Canvas c = null;  
  80.         if (!mDrawingStopped && mWindow != null) {  
  81.             if (dirty == null) {  
  82.                 if (mTmpDirty == null) {  
  83.                     mTmpDirty = new Rect();  
  84.                 }  
  85.                 mTmpDirty.set(mSurfaceFrame);  
  86.                 dirty = mTmpDirty;  
  87.             }  
  88.   
  89.             try {  
  90.                 c = mSurface.lockCanvas(dirty);  
  91.             } catch (Exception e) {  
  92.                 Log.e(LOG_TAG, "Exception locking surface", e);  
  93.             }  
  94.         }  
  95.   
  96.         if (DEBUG) Log.i(TAG, "Returned canvas: " + c);  
  97.         if (c != null) {  
  98.             mLastLockTime = SystemClock.uptimeMillis();  
  99.             return c;  
  100.         }  
  101.           
  102.         // If the Surface is not ready to be drawn, then return null,  
  103.         // but throttle calls to this function so it isn't called more  
  104.         // than every 100ms.  
  105.         long now = SystemClock.uptimeMillis();  
  106.         long nextTime = mLastLockTime + 100;  
  107.         if (nextTime > now) {  
  108.             try {  
  109.                 Thread.sleep(nextTime-now);  
  110.             } catch (InterruptedException e) {  
  111.             }  
  112.             now = SystemClock.uptimeMillis();  
  113.         }  
  114.         mLastLockTime = now;  
  115.         mSurfaceLock.unlock();  
  116.           
  117.         return null;  
  118.     }  
  119.   
  120.     public void unlockCanvasAndPost(Canvas canvas) {  
  121.         mSurface.unlockCanvasAndPost(canvas);  
  122.         mSurfaceLock.unlock();  
  123.     }  
  124.   
  125.     public Surface getSurface() {  
  126.         return mSurface;  
  127.     }  
  128.   
  129.     public Rect getSurfaceFrame() {  
  130.         return mSurfaceFrame;  
  131.     }  
  132. }  

5. 使用ProgressDialog

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.     ProgressDialog mDialog;  
  3.     MyThread mThread;  
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.main);  
  8.         // create and display the progress in a new thread  
  9.         mDialog = new ProgressDialog(MainActivity.this);    
  10.         mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);    
  11.         mDialog.setTitle("MyTitle");    
  12.         //mDialog.setIcon(R.drawable.icon);    
  13.         mDialog.setMessage("This is a progress example!");    
  14.         mDialog.setMax(100);    
  15.         mDialog.setProgress(0);    
  16.         //mDialog.setSecondaryProgress(50);    
  17.         mDialog.setIndeterminate(false);    
  18.         mDialog.setCancelable(true);    
  19.         mDialog.show();   
  20.           
  21.         mThread = new MyThread();  
  22.         mThread.start();  
  23.     }  
  24.   
  25.     public class MyThread extends Thread {  
  26.         MyThread(){  
  27.             super("MyThread");  
  28.         }  
  29.         @Override  
  30.         public void run(){  
  31.             int i=0;  
  32.             while(i<100){  
  33.                 i++;  
  34.                 // set the progress value  
  35.                 mDialog.setProgress(i);  
  36.                 try{  
  37.                     Thread.sleep(100); // sleep 1s  
  38.                 }catch(InterruptedException e){  
  39.                     e.printStackTrace();  
  40.                 }  
  41.             }  
  42.             // destroy the progress  
  43.             mDialog.dismiss();  
  44.         }  
  45.     }  
  46. }  

6. 如何使用Timer and TimerTask?

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.mytest;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import android.os.Bundle;  
  7. import android.os.Handler;  
  8. import android.os.Message;  
  9. import android.app.Activity;  
  10. import android.view.Menu;  
  11.   
  12. public class MainActivity extends Activity {  
  13.     private Timer timer = new Timer();  
  14.     private Handler h;  
  15.     private int k = 0;  
  16.       
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.           
  22.         h = new Handler(){  
  23.             public void handleMessage(Message msg) {  
  24.                 setTitle((String)msg.obj);  
  25.             }  
  26.         };   
  27.   
  28.         // init and start the timer  
  29.         init();  
  30.     }  
  31.   
  32.     public void init() {  
  33.         //public abstract class TimerTask implements Runnable  
  34.         TimerTask task = new TimerTask(){  
  35.             @Override   
  36.             public void run() {  
  37.                 h.removeMessages(0);  
  38.                 Message m = h.obtainMessage(111,Thread.currentThread().getName() + " : "+String.valueOf(k++));  
  39.                 h.sendMessage(m);  
  40.             }  
  41.         };  
  42.         // after 500ms execute task firstly, then every 1000ms execute the task  
  43.         timer.schedule(task, 5001000); //启动Timer线程  
  44.     }  
  45. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值