Android开发之--(WIFI,蓝牙,电池,背光,SD卡,摄像头,按键,MIC,重力感应等)功能的简单使用

http://blog.csdn.net/tangcheng_ok/article/details/6684646

这篇文章主要是记录前段时间开发所用到的一些技术,在这里做个总结,文中有不足之处还请看到本文的你多多指点。分享分享开发经验,一起提高!

1、WIFI(打开,关闭,使能,扫描等)

2、蓝牙(打开关闭)

3、电池(获取电池的各种参数和状态信息)

4、背光(背光调节)

5、U盘/SDcard(判断是否插入,读取等)

6、屏幕校准(准确的说是点击屏幕的准确度,不是校准屏幕,这是一个简单的算法,这里只提供思路了:屏幕上放5个Button,分别位于左上;左下;右上;右下;获取图片所在屏幕的位置,和图片的长宽,在用户点击Button时获取点击的坐标位置,进行判断。这种方式可能不正确,希望看到这篇文章的各位前辈大哥指点)

7、振动马达(简单的调用振动马达的服务)

8、摄像头(简单的预览图像)

9、按键(获取用户点击的按键,包括Home按键)

10、音乐(使用MediaPlayer调用音频文件播放)

11、MIC(获得当前录音的振幅和录制音频文件)

12、重力感应(通过监听方式获取X、Y、Z三点坐标的值)

    以上是对本文提到的几个基本功能的简单介绍,如果你看到此处说明很期待下文。哈哈,且看一下代码!记住这里只是一些基本功能的使用,至于要实现其他的效果,还是要看自己好好研究了。一般看看API和提供的DEMO都能解决的。

    1、WIFI

[java] view plaincopy
  1. package cn.tch;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.content.Context;  
  6. import android.net.wifi.ScanResult;  
  7. import android.net.wifi.WifiConfiguration;  
  8. import android.net.wifi.WifiInfo;  
  9. import android.net.wifi.WifiManager;  
  10. import android.net.wifi.WifiManager.WifiLock;  
  11.   
  12. public class WifiHelper {  
  13.     // 定义WifiManager对象  
  14.     private WifiManager mWifiManager;  
  15.     // 定义WifiInfo对象  
  16.     private WifiInfo mWifiInfo;  
  17.     // 扫描出的网络连接列表  
  18.     private List<ScanResult> mWifiList;  
  19.     // 网络连接列表  
  20.     private List<WifiConfiguration> mWifiConfiguration;  
  21.     // 定义一个WifiLock  
  22.     WifiLock mWifiLock;  
  23.   
  24.     // 构造器  
  25.     public WifiHelper(Context context) {  
  26.         // 取得WifiManager对象  
  27.         mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
  28.         // 取得WifiInfo对象  
  29.         mWifiInfo = mWifiManager.getConnectionInfo();  
  30.     }  
  31.       
  32.     public WifiManager getWifiManager(){  
  33.         return mWifiManager;  
  34.     }  
  35.   
  36.     // 打开WIFI  
  37.     public boolean openWifi() {  
  38.         boolean flag = false;  
  39.         if (!mWifiManager.isWifiEnabled()) {  
  40.             flag =  mWifiManager.setWifiEnabled(true);  
  41.         }else if(mWifiManager.isWifiEnabled()){  
  42.             flag = true;  
  43.         }  
  44.         return flag;  
  45.     }  
  46.   
  47.     // 关闭WIFI  
  48.     public void closeWifi() {  
  49.         if (!mWifiManager.isWifiEnabled()) {  
  50.             mWifiManager.setWifiEnabled(false);  
  51.         }  
  52.     }  
  53.   
  54.     // 锁定WifiLock  
  55.     public void acquireWifiLock() {  
  56.         mWifiLock.acquire();  
  57.     }  
  58.   
  59.     // 解锁WifiLock  
  60.     public void releaseWifiLock() {  
  61.         // 判断时候锁定  
  62.         if (mWifiLock.isHeld()) {  
  63.             mWifiLock.acquire();  
  64.         }  
  65.     }  
  66.   
  67.     // 创建一个WifiLock  
  68.     public void creatWifiLock() {  
  69.         mWifiLock = mWifiManager.createWifiLock("Test");  
  70.     }  
  71.   
  72.     // 得到配置好的网络  
  73.     public List<WifiConfiguration> getConfiguration() {  
  74.         return mWifiConfiguration;  
  75.     }  
  76.   
  77.     // 指定配置好的网络进行连接  
  78.     public void connectConfiguration(int index) {  
  79.         // 索引大于配置好的网络索引返回  
  80.         if (index > mWifiConfiguration.size()) {  
  81.             return;  
  82.         }  
  83.         // 连接配置好的指定ID的网络  
  84.         mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true);  
  85.     }  
  86.   
  87.     public void startScan() {  
  88.         mWifiManager.startScan();  
  89.         // 得到扫描结果  
  90.         mWifiList = mWifiManager.getScanResults();  
  91.         // 得到配置好的网络连接  
  92.         mWifiConfiguration = mWifiManager.getConfiguredNetworks();  
  93.     }  
  94.   
  95.     // 得到网络列表  
  96.     public List<ScanResult> getWifiList() {  
  97.         mWifiManager.startScan();  
  98.         // 得到扫描结果  
  99.         return mWifiManager.getScanResults();  
  100.     }  
  101.   
  102.     // 查看扫描结果  
  103.     public StringBuilder lookUpScan(List<ScanResult> list) {  
  104.         StringBuilder stringBuilder = new StringBuilder();  
  105.         for (int i = 0; i < list.size(); i++) {  
  106.             stringBuilder  
  107.                     .append("\n    结果" + new Integer(i + 1).toString() + " (");  
  108.             // 将ScanResult信息转换成一个字符串包  
  109.             // 其中把包括:BSSID、SSID、capabilities、frequency、level  
  110.             stringBuilder.append((list.get(i)).toString());  
  111.             stringBuilder.append(")\n");  
  112.         }  
  113.         return stringBuilder;  
  114.     }  
  115.   
  116.     // 得到MAC地址  
  117.     public String getMacAddress() {  
  118.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();  
  119.     }  
  120.   
  121.     // 得到接入点的BSSID  
  122.     public String getBSSID() {  
  123.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();  
  124.     }  
  125.   
  126.     // 得到IP地址  
  127.     public int getIPAddress() {  
  128.         return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();  
  129.     }  
  130.   
  131.     // 得到连接的ID  
  132.     public int getNetworkId() {  
  133.         return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();  
  134.     }  
  135.   
  136.     // 得到WifiInfo的所有信息包  
  137.     public String getWifiInfo() {  
  138.         return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();  
  139.     }  
  140.   
  141.     // 添加一个网络并连接  
  142.     public void addNetwork(WifiConfiguration wcg) {  
  143.         int wcgID = mWifiManager.addNetwork(wcg);  
  144.         mWifiManager.enableNetwork(wcgID, true);  
  145.     }  
  146.   
  147.     // 断开指定ID的网络  
  148.     public void disconnectWifi(int netId) {  
  149.         mWifiManager.disableNetwork(netId);  
  150.         mWifiManager.disconnect();  
  151.     }  
  152.   
  153.       
  154. }  

2、蓝牙

[java] view plaincopy
  1. boolean flag = false;  
  2. lt;pre class="java" name="code">        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
if (bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); flag = bluetoothAdapter.enable(); } else { flag = bluetoothAdapter.enable(); }

3、电池

1、新建一个广播接收类

[java] view plaincopy
  1. package cn.tch;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.content.res.Resources;  
  7. import android.os.BatteryManager;  
  8. import android.util.Log;  
  9.   
  10. import java.util.ArrayList;  
  11.   
  12. public class BatteryBroadcastReceiver extends BroadcastReceiver {  
  13.   
  14.     private String action;  
  15.     private int status;  
  16.     private int health;  
  17.     private int plugged;  
  18.     private String statusString;  
  19.     private String healthString;  
  20.     private String acString;  
  21.     private Resources mResources;  
  22.     private StringBuffer buffer = new StringBuffer();  
  23.     private static int count = 0;  
  24.     private ArrayList<String> batteryMsg;  
  25.   
  26.     int level;// 电池电量,数字  
  27.     int scale;// 电池最大容量  
  28.     int voltage;// 电池伏数  
  29.     int temperature;// 电池温度  
  30.       
  31.     public BatteryBroadcastReceiver(Resources res) {  
  32.         mResources = res;  
  33.         batteryMsg  = new ArrayList<String>();  
  34.     }  
  35.   
  36.     @Override  
  37.     public void onReceive(Context context, Intent intent) {  
  38.         action = intent.getAction();  
  39.         status = intent.getIntExtra("status"0);  
  40.         health = intent.getIntExtra("health"0);  
  41.         plugged = intent.getIntExtra("plugged"0);  
  42.         switch (status) {  
  43.             case BatteryManager.BATTERY_STATUS_UNKNOWN:  
  44.                 statusString = "unknown";  
  45.                 break;  
  46.             case BatteryManager.BATTERY_STATUS_CHARGING:  
  47.                 statusString = "charging";  
  48.                 break;  
  49.             case BatteryManager.BATTERY_STATUS_DISCHARGING:  
  50.                 statusString = "discharging";  
  51.                 break;  
  52.             case BatteryManager.BATTERY_STATUS_NOT_CHARGING:  
  53.                 statusString = "not charging";  
  54.                 break;  
  55.             case BatteryManager.BATTERY_STATUS_FULL:  
  56.                 statusString = "full";  
  57.                 break;  
  58.         }  
  59.   
  60.         switch (health) {  
  61.             case BatteryManager.BATTERY_HEALTH_UNKNOWN:  
  62.                 healthString = "unknown";  
  63.                 break;  
  64.             case BatteryManager.BATTERY_HEALTH_GOOD:  
  65.                 healthString = "good";  
  66.                 break;  
  67.             case BatteryManager.BATTERY_HEALTH_OVERHEAT:  
  68.                 healthString = "overheat";  
  69.                 break;  
  70.             case BatteryManager.BATTERY_HEALTH_DEAD:  
  71.                 healthString = "dead";  
  72.                 break;  
  73.             case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:  
  74.                 healthString = "voltage";  
  75.                 break;  
  76.             case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:  
  77.                 healthString = "unspecified failure";  
  78.                 break;  
  79.         }  
  80.         switch (plugged) {  
  81.             case BatteryManager.BATTERY_PLUGGED_AC:  
  82.                 acString = "plugged ac";  
  83.                 break;  
  84.             case BatteryManager.BATTERY_PLUGGED_USB:  
  85.                 acString = "plugged usb";  
  86.                 break;  
  87.         }  
  88. //        if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {  
  89. //            for (int i = count; i < 10; i++) {  
  90. //                level = intent.getIntExtra("level", 0);// 电池电量,数字  
  91. //                scale = intent.getIntExtra("scale", 0);// 电池最大容量  
  92. //                voltage = intent.getIntExtra("voltage", 0);// 电池伏数  
  93. //                temperature = intent.getIntExtra("temperature", 0);// 电池温度  
  94. //                String msg = String.format(res.getString(R.string.battery_chenged_msg), level, scale, voltage,  
  95. //                        temperature, statusString, acString, healthString);  
  96. //                batteryMsg.add(msg);  
  97. //                count++;  
  98. //            }  
  99. //        }  
  100.     }  
  101.       
  102.   
  103.     // 电池状态,返回是一个数字  
  104.     // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态  
  105.     // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中  
  106.     // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电  
  107.     // BatteryManager.BATTERY_STATUS_FULL 电池满  
  108.     // 充电类型 BatteryManager.BATTERY_PLUGGED_AC 表示是充电器,不是这个值,表示是 USB  
  109.     // 电池健康情况,返回也是一个数字  
  110.     // BatteryManager.BATTERY_HEALTH_GOOD 良好  
  111.     // BatteryManager.BATTERY_HEALTH_OVERHEAT 过热  
  112.     // BatteryManager.BATTERY_HEALTH_DEAD 没电  
  113.     // BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压  
  114.     // BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误  
  115. }  

2、注册广播

[java] view plaincopy
  1. IntentFilter intentFilter = new IntentFilter();  
  2.         intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
  3.         registerReceiver(batteryReceiver, intentFilter);  

4、背光

[java] view plaincopy
  1. package cn.tch;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.AlertDialog;  
  5. import android.content.DialogInterface;  
  6. import android.content.Intent;  
  7. import android.content.res.Resources;  
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.os.Message;  
  11. import android.os.RemoteException;  
  12. import android.provider.Settings;  
  13. import android.provider.Settings.SettingNotFoundException;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.widget.Button;  
  18. import android.widget.ProgressBar;  
  19. import android.widget.SeekBar;  
  20. import android.widget.SeekBar.OnSeekBarChangeListener;  
  21. import android.os.IPowerManager;  
  22. import android.os.ServiceManager;  
  23.   
  24. import static cn.tch.Constant.*;  
  25.   
  26. public class BacklightActivity extends Activity implements OnSeekBarChangeListener{  
  27.   
  28.     private final static String TAG = "BacklightActivity";  
  29.     private SeekBar seekBar;  
  30.     private Button btnFinish;  
  31.     private Resources res;  
  32.       
  33.     private int mOldBrightness = 0;  
  34.     private static final int MINIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_DIM + 10;  
  35.     private static final int MAXIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_ON;  
  36.       
  37.     private boolean isRun = true;  
  38.       
  39.     @Override  
  40.     protected void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.           
  43.         setContentView(R.layout.backlight);  
  44.         res = getResources();  
  45.         seekBar = (SeekBar) findViewById(R.id.bl_seekbar);  
  46.         btnFinish = (Button) findViewById(R.id.bl_finish);  
  47.         initBrightness();  
  48.           
  49.           
  50.         seekBar.setOnSeekBarChangeListener(this);  
  51.         btnFinish.setOnClickListener(new OnClickListener() {  
  52.               
  53.             //@Override  
  54.             public void onClick(View v) {  
  55.                 new AlertDialog.Builder(BacklightActivity.this).setIcon(  
  56.                         R.drawable.icon).setTitle(res.getString(R.string.backlight_title))  
  57.                         .setMessage(res.getString(R.string.backlight_msg)).setPositiveButton(  
  58.                                 res.getString(R.string.yes), dialogClick)  
  59.                         .setNegativeButton(res.getString(R.string.no), dialogClick).create().show();  
  60.             }  
  61.         });  
  62.           
  63.           
  64.     }  
  65.       
  66.       
  67.     private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() {  
  68.   
  69.         //@Override  
  70.         public void onClick(DialogInterface dialog, int which) {  
  71.             switch (which) {  
  72.             case DialogInterface.BUTTON_POSITIVE:  
  73.                 resultRquest(true);  
  74.                 break;  
  75.             case DialogInterface.BUTTON_NEGATIVE:  
  76.                 resultRquest(false);  
  77.                 break;  
  78.             default:  
  79.                 break;  
  80.             }  
  81.         }  
  82.     };  
  83.       
  84.     private void resultRquest(boolean flag){  
  85.         Intent intent = new Intent(this, MainActivity.class);  
  86.         intent.putExtra(BACKLIGHT_RESULT,flag);  
  87.         setResult(REQUESTCODE_BACKLIGHT_RESULT, intent);  
  88.         finish();  
  89.     }  
  90.   
  91.     //@Override  
  92.     public void onProgressChanged(SeekBar seekBar, int progress,  
  93.             boolean fromUser) {  
  94.         int step = 25;  
  95.         Settings.System.putInt(BacklightActivity.this.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, progress + MINIMUM_BACKLIGHT);  
  96.         setBrightness(progress + MINIMUM_BACKLIGHT);  
  97.     }  
  98.       
  99.     private void initBrightness(){  
  100.         // 获取当前背光亮度  
  101.         try {  
  102.             mOldBrightness = Settings.System.getInt(BacklightActivity.this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);  
  103.         } catch (SettingNotFoundException e) {  
  104.             mOldBrightness = MAXIMUM_BACKLIGHT;  
  105.         }  
  106.         seekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT);  
  107.         Log.v("Brightness max""setmax:" + (MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT));  
  108.         //seekBar.setProgress(mOldBrightness - MINIMUM_BACKLIGHT);  
  109.         seekBar.setProgress(0);  
  110.           
  111.         new Thread(new Runnable() {  
  112.             int value = 0;  
  113.             public void run() {  
  114.                 while (isRun) {  
  115.                     try {  
  116.                         Thread.sleep(150);  
  117.                         value = value+5;   
  118.                         Message message = new Message();  
  119.                         message.what = value;  
  120.                         handler.sendEmptyMessage(message.what);  
  121.                     } catch (InterruptedException e) {  
  122.                     }  
  123.                 }  
  124.             }  
  125.         }).start();  
  126.     }   
  127.       
  128.     private Handler handler = new Handler(){  
  129.         public void handleMessage(android.os.Message msg) {  
  130.             if(msg.what<=MAXIMUM_BACKLIGHT){  
  131.                 seekBar.setProgress(msg.what);  
  132. //              Settings.System.putInt(BacklightActivity.this.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, msg.what + MINIMUM_BACKLIGHT);       
  133.                 setBrightness(msg.what);  
  134.             }else{  
  135.                 isRun = false;  
  136.             }  
  137.              
  138.         };  
  139.     };  
  140.       
  141.     private void setBrightness(int brightness) {  
  142.         try {  
  143.             IPowerManager power = IPowerManager.Stub.asInterface(ServiceManager.getService("power"));  
  144.             if (power != null) {  
  145.                 power.setBacklightBrightness(brightness);  
  146.             }  
  147.         } catch (RemoteException doe) {  
  148.             Log.e(TAG,"Setting Brightness RemoteException!");         
  149.         }          
  150.     }  
  151.       
  152.     //@Override  
  153.     public void onStartTrackingTouch(SeekBar seekBar) {}  
  154.   
  155.     //@Override  
  156.     public void onStopTrackingTouch(SeekBar seekBar) {}  
  157. }  

5、判断SDcard和获取SDCard的路径

[java] view plaincopy
  1. static String getSdcardPath(){  
  2.     return Environment.getExternalStorageDirectory().getPath();  
  3. }  
  4.   
  5. static boolean checkSdcard(){  
  6.     boolean flag = false;  
  7.     if(Environment.getExternalStorageDirectory().toString().equals("/mnt/sdcard")){  
  8.         flag = true;  
  9.     }  
  10.     return flag;  
  11. }  

6、屏幕校准(请参看前面说明)

7、振动马达

[java] view plaincopy
  1. vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
  2.        long[] pattern = {  
  3.                8005040030  
  4.        }; // OFF/ON/OFF/ON...  
  5.        vibrator.vibrate(pattern, 2);  

8、摄像头(拍照和预览)

[java] view plaincopy
  1. public class CameraActivity extends Activity{  
  2.     /** 
  3.      * 第一种方式实现拍照 
  4.      */  
  5.     // private PreView preView = null;  
  6.     //  
  7.     // @Override  
  8.     // protected void onCreate(Bundle savedInstanceState) {  
  9.     // super.onCreate(savedInstanceState);  
  10.     // this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  11.     // preView = new PreView(this);  
  12.     // setContentView(preView,new LayoutParams(400, 300));  
  13.     // }  
  14.     //  
  15.     // @Override  
  16.     // public boolean onKeyDown(int keyCode, KeyEvent event) {  
  17.     // return preView.onKeyDown(keyCode, event);  
  18.     // }  
  19.   
  20.     private final static String TAG = "CameraActivity";  
  21.     private SurfaceView surfaceView;  
  22.     private SurfaceHolder surfaceHolder;  
  23.     private Camera camera;  
  24.     private File picture;  
  25.       
  26.     private Button btnFinish;  
  27.       
  28.     private Dialog mDialog;  
  29.     private Resources res;  
  30.   
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.          this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  35.         setContentView(R.layout.camera);  
  36.         setupViews();  
  37.     }  
  38.       
  39.     private void setupViews(){  
  40.         surfaceView = (SurfaceView) findViewById(R.id.camera_preview); // 实例化拍照界面组件  
  41.         surfaceHolder = surfaceView.getHolder(); // 实例化拍照界面组件  
  42.         surfaceHolder.addCallback(surfaceCallback); // 为SurfaceHolder 添加回调  
  43.         surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
  44.         res = getResources();  
  45.         btnFinish =(Button) findViewById(R.id.camera_finish);  
  46.           
  47.         btnFinish.setOnClickListener(new OnClickListener() {  
  48.               
  49.             //@Override  
  50.             public void onClick(View v) {  
  51.                   
  52.                 // 提示是否看到预览  
  53.                 if(mDialog == null){  
  54.                 mDialog = new AlertDialog.Builder(CameraActivity.this).setIcon(  
  55.                         R.drawable.icon).setTitle(res.getString(R.string.camera_title))  
  56.                         .setMessage(res.getString(R.string.camera_msg)).setPositiveButton(  
  57.                                 res.getString(R.string.yes), dialogClick)  
  58.                         .setNegativeButton(res.getString(R.string.no), dialogClick).create();  
  59.                 mDialog.show();}  
  60.             }  
  61.         });  
  62.     }  
  63.       
  64.        private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() {  
  65.   
  66. //        @Override  
  67.             public void onClick(DialogInterface dialog, int which) {  
  68.                 switch (which) {  
  69.                 case DialogInterface.BUTTON_POSITIVE:  
  70.                     resultRquest(true);  
  71.                     break;  
  72.                 case DialogInterface.BUTTON_NEGATIVE:  
  73.                     resultRquest(false);  
  74.                     break;  
  75.                 default:  
  76.                     break;  
  77.                 }  
  78.   
  79.             }  
  80.         };  
  81.           
  82.         private void resultRquest(boolean flag){  
  83.             Intent intent = new Intent(CameraActivity.this, MainActivity.class);  
  84.             intent.putExtra(CAMERA_RESULT, flag);  
  85.             setResult(REQUESTCODE_CAMERA_RESULT, intent);  
  86.             finish();  
  87.         }  
  88.   
  89.     @Override  
  90.     public boolean onKeyDown(int keyCode, KeyEvent event) {  
  91.         if (keyCode == KeyEvent.KEYCODE_CAMERA  
  92.                 || keyCode == KeyEvent.KEYCODE_SEARCH) {  
  93.             takePic();  
  94.             return true;  
  95.         }  
  96.         return super.onKeyDown(keyCode, event);  
  97.     }  
  98.   
  99.     private void takePic() {  
  100.   
  101.         camera.stopPreview();// 停止预览  
  102.   
  103.         camera.takePicture(nullnull, pictureCallback); // 拍照  
  104.     }  
  105.   
  106.     // 照片回调  
  107.     Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {  
  108.         //@Override  
  109.         public void onPictureTaken(byte[] data, Camera camera) {  
  110.             new SavePictureTask().execute(data);  
  111.             camera.startPreview();  
  112.         }  
  113.     };  
  114.   
  115.     // 保存照片任务类  
  116.     class SavePictureTask extends AsyncTask<byte[], String, String> {  
  117.         @Override  
  118.         protected String doInBackground(byte[]... params) {  
  119.   
  120.             picture = new File(Environment.getExternalStorageDirectory(),  
  121.                     "picture.jpg");// 创建文件  
  122.   
  123.             if (picture.exists())  
  124.                 picture.delete(); // 如果文件存在删除掉  
  125.             try {  
  126.                 FileOutputStream fos = new FileOutputStream(picture.getPath()); // 获得文件输出流  
  127.                 fos.write(params[0]); // 写到该文件  
  128.                 fos.close(); // 关闭文件流  
  129.             } catch (Exception e) {  
  130.                 e.printStackTrace();  
  131.             }  
  132.             return null;  
  133.         }  
  134.     }  
  135.   
  136.     // SurfaceHodler 回调,处理打开相机,关闭相机以及照片尺寸的改变  
  137.     SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {  
  138.         //@Override  
  139.         public void surfaceCreated(SurfaceHolder holder) {  
  140.             camera = Camera.open(); // 打开相机  
  141.             try {  
  142.                 camera.setPreviewDisplay(holder); // 设置预览  
  143.             } catch (IOException e) {  
  144.                 camera.release();// 释放  
  145.                 camera = null;  
  146.             }  
  147.         }  
  148.   
  149.         //@Override  
  150.         public void surfaceChanged(SurfaceHolder holder, int format, int width,  
  151.                 int height) {  
  152.             Camera.Parameters parameters = camera.getParameters(); // 获得相机参数  
  153.             parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片格式  
  154.             parameters.setPreviewSize(400300); // 设置照片大小  
  155.             camera.setParameters(parameters); // 设置相机参数  
  156.             camera.startPreview(); // 开始预览  
  157.               
  158.         }  
  159.   
  160.         //@Override  
  161.         public void surfaceDestroyed(SurfaceHolder holder) {  
  162.             Log.i(TAG,"====surfaceDestroyed");  
  163.             camera.stopPreview();// 停止预览  
  164.             camera.release(); // 释放相机资源  
  165.             camera = null;  
  166.         }  
  167.     };  
  168.   
  169.       
  170. }  

9、按键(只要重写dispoatchKeyEvent即可)

以下是屏蔽Home键的方法:
[java] view plaincopy
  1. @Override  
  2.     public void onAttachedToWindow() {  
  3.         this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);     
  4.         super.onAttachedToWindow();       
  5.     }  

10、音乐播放器

11、录音

[java] view plaincopy