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

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

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

view plain copy to clipboard print ?
  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. }  
package cn.tch; import java.util.List; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; public class WifiHelper { // 定义WifiManager对象 private WifiManager mWifiManager; // 定义WifiInfo对象 private WifiInfo mWifiInfo; // 扫描出的网络连接列表 private List<ScanResult> mWifiList; // 网络连接列表 private List<WifiConfiguration> mWifiConfiguration; // 定义一个WifiLock WifiLock mWifiLock; // 构造器 public WifiHelper(Context context) { // 取得WifiManager对象 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // 取得WifiInfo对象 mWifiInfo = mWifiManager.getConnectionInfo(); } public WifiManager getWifiManager(){ return mWifiManager; } // 打开WIFI public boolean openWifi() { boolean flag = false; if (!mWifiManager.isWifiEnabled()) { flag = mWifiManager.setWifiEnabled(true); }else if(mWifiManager.isWifiEnabled()){ flag = true; } return flag; } // 关闭WIFI public void closeWifi() { if (!mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } // 锁定WifiLock public void acquireWifiLock() { mWifiLock.acquire(); } // 解锁WifiLock public void releaseWifiLock() { // 判断时候锁定 if (mWifiLock.isHeld()) { mWifiLock.acquire(); } } // 创建一个WifiLock public void creatWifiLock() { mWifiLock = mWifiManager.createWifiLock("Test"); } // 得到配置好的网络 public List<WifiConfiguration> getConfiguration() { return mWifiConfiguration; } // 指定配置好的网络进行连接 public void connectConfiguration(int index) { // 索引大于配置好的网络索引返回 if (index > mWifiConfiguration.size()) { return; } // 连接配置好的指定ID的网络 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,true); } public void startScan() { mWifiManager.startScan(); // 得到扫描结果 mWifiList = mWifiManager.getScanResults(); // 得到配置好的网络连接 mWifiConfiguration = mWifiManager.getConfiguredNetworks(); } // 得到网络列表 public List<ScanResult> getWifiList() { mWifiManager.startScan(); // 得到扫描结果 return mWifiManager.getScanResults(); } // 查看扫描结果 public StringBuilder lookUpScan(List<ScanResult> list) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < list.size(); i++) { stringBuilder .append("\n 结果" + new Integer(i + 1).toString() + " ("); // 将ScanResult信息转换成一个字符串包 // 其中把包括:BSSID、SSID、capabilities、frequency、level stringBuilder.append((list.get(i)).toString()); stringBuilder.append(")\n"); } return stringBuilder; } // 得到MAC地址 public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } // 得到接入点的BSSID public String getBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } // 得到IP地址 public int getIPAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } // 得到连接的ID public int getNetworkId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } // 得到WifiInfo的所有信息包 public String getWifiInfo() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString(); } // 添加一个网络并连接 public void addNetwork(WifiConfiguration wcg) { int wcgID = mWifiManager.addNetwork(wcg); mWifiManager.enableNetwork(wcgID, true); } // 断开指定ID的网络 public void disconnectWifi(int netId) { mWifiManager.disableNetwork(netId); mWifiManager.disconnect(); } }

2、蓝牙

view plain copy to clipboard print ?
  1. boolean flag = false;  
  2. lt;pre class="java" name="code">        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
boolean flag = false; <pre class="java" name="code"> BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); flag = bluetoothAdapter.enable(); } else { flag = bluetoothAdapter.enable(); }
 
 

 
 

3、电池

1、新建一个广播接收类

view plain copy to clipboard print ?
  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. }  
package cn.tch; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.BatteryManager; import android.util.Log; import java.util.ArrayList; public class BatteryBroadcastReceiver extends BroadcastReceiver { private String action; private int status; private int health; private int plugged; private String statusString; private String healthString; private String acString; private Resources mResources; private StringBuffer buffer = new StringBuffer(); private static int count = 0; private ArrayList<String> batteryMsg; int level;// 电池电量,数字 int scale;// 电池最大容量 int voltage;// 电池伏数 int temperature;// 电池温度 public BatteryBroadcastReceiver(Resources res) { mResources = res; batteryMsg = new ArrayList<String>(); } @Override public void onReceive(Context context, Intent intent) { action = intent.getAction(); status = intent.getIntExtra("status", 0); health = intent.getIntExtra("health", 0); plugged = intent.getIntExtra("plugged", 0); switch (status) { case BatteryManager.BATTERY_STATUS_UNKNOWN: statusString = "unknown"; break; case BatteryManager.BATTERY_STATUS_CHARGING: statusString = "charging"; break; case BatteryManager.BATTERY_STATUS_DISCHARGING: statusString = "discharging"; break; case BatteryManager.BATTERY_STATUS_NOT_CHARGING: statusString = "not charging"; break; case BatteryManager.BATTERY_STATUS_FULL: statusString = "full"; break; } switch (health) { case BatteryManager.BATTERY_HEALTH_UNKNOWN: healthString = "unknown"; break; case BatteryManager.BATTERY_HEALTH_GOOD: healthString = "good"; break; case BatteryManager.BATTERY_HEALTH_OVERHEAT: healthString = "overheat"; break; case BatteryManager.BATTERY_HEALTH_DEAD: healthString = "dead"; break; case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: healthString = "voltage"; break; case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: healthString = "unspecified failure"; break; } switch (plugged) { case BatteryManager.BATTERY_PLUGGED_AC: acString = "plugged ac"; break; case BatteryManager.BATTERY_PLUGGED_USB: acString = "plugged usb"; break; } // if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { // for (int i = count; i < 10; i++) { // level = intent.getIntExtra("level", 0);// 电池电量,数字 // scale = intent.getIntExtra("scale", 0);// 电池最大容量 // voltage = intent.getIntExtra("voltage", 0);// 电池伏数 // temperature = intent.getIntExtra("temperature", 0);// 电池温度 // String msg = String.format(res.getString(R.string.battery_chenged_msg), level, scale, voltage, // temperature, statusString, acString, healthString); // batteryMsg.add(msg); // count++; // } // } } // 电池状态,返回是一个数字 // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态 // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中 // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电 // BatteryManager.BATTERY_STATUS_FULL 电池满 // 充电类型 BatteryManager.BATTERY_PLUGGED_AC 表示是充电器,不是这个值,表示是 USB // 电池健康情况,返回也是一个数字 // BatteryManager.BATTERY_HEALTH_GOOD 良好 // BatteryManager.BATTERY_HEALTH_OVERHEAT 过热 // BatteryManager.BATTERY_HEALTH_DEAD 没电 // BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压 // BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误 }

2、注册广播

view plain copy to clipboard print ?
  1. IntentFilter intentFilter = new IntentFilter();  
  2.         intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
  3.         registerReceiver(batteryReceiver, intentFilter);  
IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryReceiver, intentFilter);

4、背光

view plain copy to clipboard print ?
  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. }  
package cn.tch; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.os.IPowerManager; import android.os.ServiceManager; import static cn.tch.Constant.*; public class BacklightActivity extends Activity implements OnSeekBarChangeListener{ private final static String TAG = "BacklightActivity"; private SeekBar seekBar; private Button btnFinish; private Resources res; private int mOldBrightness = 0; private static final int MINIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_DIM + 10; private static final int MAXIMUM_BACKLIGHT = android.os.Power.BRIGHTNESS_ON; private boolean isRun = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.backlight); res = getResources(); seekBar = (SeekBar) findViewById(R.id.bl_seekbar); btnFinish = (Button) findViewById(R.id.bl_finish); initBrightness(); seekBar.setOnSeekBarChangeListener(this); btnFinish.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { new AlertDialog.Builder(BacklightActivity.this).setIcon( R.drawable.icon).setTitle(res.getString(R.string.backlight_title)) .setMessage(res.getString(R.string.backlight_msg)).setPositiveButton( res.getString(R.string.yes), dialogClick) .setNegativeButton(res.getString(R.string.no), dialogClick).create().show(); } }); } private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() { //@Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: resultRquest(true); break; case DialogInterface.BUTTON_NEGATIVE: resultRquest(false); break; default: break; } } }; private void resultRquest(boolean flag){ Intent intent = new Intent(this, MainActivity.class); intent.putExtra(BACKLIGHT_RESULT,flag); setResult(REQUESTCODE_BACKLIGHT_RESULT, intent); finish(); } //@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int step = 25; Settings.System.putInt(BacklightActivity.this.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, progress + MINIMUM_BACKLIGHT); setBrightness(progress + MINIMUM_BACKLIGHT); } private void initBrightness(){ // 获取当前背光亮度 try { mOldBrightness = Settings.System.getInt(BacklightActivity.this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { mOldBrightness = MAXIMUM_BACKLIGHT; } seekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT); Log.v("Brightness max", "setmax:" + (MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT)); //seekBar.setProgress(mOldBrightness - MINIMUM_BACKLIGHT); seekBar.setProgress(0); new Thread(new Runnable() { int value = 0; public void run() { while (isRun) { try { Thread.sleep(150); value = value+5; Message message = new Message(); message.what = value; handler.sendEmptyMessage(message.what); } catch (InterruptedException e) { } } } }).start(); } private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what<=MAXIMUM_BACKLIGHT){ seekBar.setProgress(msg.what); // Settings.System.putInt(BacklightActivity.this.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, msg.what + MINIMUM_BACKLIGHT); setBrightness(msg.what); }else{ isRun = false; } }; }; private void setBrightness(int brightness) { try { IPowerManager power = IPowerManager.Stub.asInterface(ServiceManager.getService("power")); if (power != null) { power.setBacklightBrightness(brightness); } } catch (RemoteException doe) { Log.e(TAG,"Setting Brightness RemoteException!"); } } //@Override public void onStartTrackingTouch(SeekBar seekBar) {} //@Override public void onStopTrackingTouch(SeekBar seekBar) {} }

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

view plain copy to clipboard print ?
  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. }  
static String getSdcardPath(){ return Environment.getExternalStorageDirectory().getPath(); } static boolean checkSdcard(){ boolean flag = false; if(Environment.getExternalStorageDirectory().toString().equals("/mnt/sdcard")){ flag = true; } return flag; }

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

7、振动马达

view plain copy to clipboard print ?
  1. vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
  2.        long[] pattern = {  
  3.                8005040030  
  4.        }; // OFF/ON/OFF/ON...   
  5.        vibrator.vibrate(pattern, 2);  
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); long[] pattern = { 800, 50, 400, 30 }; // OFF/ON/OFF/ON... vibrator.vibrate(pattern, 2);

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

view plain copy to clipboard print ?
  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. }  
public class CameraActivity extends Activity{ /** * 第一种方式实现拍照 */ // private PreView preView = null; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); // preView = new PreView(this); // setContentView(preView,new LayoutParams(400, 300)); // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // return preView.onKeyDown(keyCode, event); // } private final static String TAG = "CameraActivity"; private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Camera camera; private File picture; private Button btnFinish; private Dialog mDialog; private Resources res; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.camera); setupViews(); } private void setupViews(){ surfaceView = (SurfaceView) findViewById(R.id.camera_preview); // 实例化拍照界面组件 surfaceHolder = surfaceView.getHolder(); // 实例化拍照界面组件 surfaceHolder.addCallback(surfaceCallback); // 为SurfaceHolder 添加回调 surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); res = getResources(); btnFinish =(Button) findViewById(R.id.camera_finish); btnFinish.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { // 提示是否看到预览 if(mDialog == null){ mDialog = new AlertDialog.Builder(CameraActivity.this).setIcon( R.drawable.icon).setTitle(res.getString(R.string.camera_title)) .setMessage(res.getString(R.string.camera_msg)).setPositiveButton( res.getString(R.string.yes), dialogClick) .setNegativeButton(res.getString(R.string.no), dialogClick).create(); mDialog.show();} } }); } private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() { // @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: resultRquest(true); break; case DialogInterface.BUTTON_NEGATIVE: resultRquest(false); break; default: break; } } }; private void resultRquest(boolean flag){ Intent intent = new Intent(CameraActivity.this, MainActivity.class); intent.putExtra(CAMERA_RESULT, flag); setResult(REQUESTCODE_CAMERA_RESULT, intent); finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_SEARCH) { takePic(); return true; } return super.onKeyDown(keyCode, event); } private void takePic() { camera.stopPreview();// 停止预览 camera.takePicture(null, null, pictureCallback); // 拍照 } // 照片回调 Camera.PictureCallback pictureCallback = new Camera.PictureCallback() { //@Override public void onPictureTaken(byte[] data, Camera camera) { new SavePictureTask().execute(data); camera.startPreview(); } }; // 保存照片任务类 class SavePictureTask extends AsyncTask<byte[], String, String> { @Override protected String doInBackground(byte[]... params) { picture = new File(Environment.getExternalStorageDirectory(), "picture.jpg");// 创建文件 if (picture.exists()) picture.delete(); // 如果文件存在删除掉 try { FileOutputStream fos = new FileOutputStream(picture.getPath()); // 获得文件输出流 fos.write(params[0]); // 写到该文件 fos.close(); // 关闭文件流 } catch (Exception e) { e.printStackTrace(); } return null; } } // SurfaceHodler 回调,处理打开相机,关闭相机以及照片尺寸的改变 SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() { //@Override public void surfaceCreated(SurfaceHolder holder) { camera = Camera.open(); // 打开相机 try { camera.setPreviewDisplay(holder); // 设置预览 } catch (IOException e) { camera.release();// 释放 camera = null; } } //@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Camera.Parameters parameters = camera.getParameters(); // 获得相机参数 parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片格式 parameters.setPreviewSize(400, 300); // 设置照片大小 camera.setParameters(parameters); // 设置相机参数 camera.startPreview(); // 开始预览 } //@Override public void surfaceDestroyed(SurfaceHolder holder) { Log.i(TAG,"====surfaceDestroyed"); camera.stopPreview();// 停止预览 camera.release(); // 释放相机资源 camera = null; } }; }

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

以下是屏蔽Home键的方法:
view plain copy to clipboard print ?
  1. @Override  
  2.     public void onAttachedToWindow() {  
  3.         this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);     
  4.         super.onAttachedToWindow();       
  5.     }  
@Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }

10、音乐播放器

代码太多了,给个给力的连接吧! http://hi.baidu.com/orangejackylee/blog/item/6afb84d68e36cbd0a9ec9a36.html/cmtid/ce7e663d9938dffdb211c7d6

11、录音

view plain copy to clipboard print ?
  1. public class MicActivity extends Activity implements OnClickListener{  
  2.   
  3.     private final static String TAG="MicActivity";  
  4.       
  5.     private Button btnMicRecord;  
  6.     private Button btnMicPlay;  
  7.     private Button btnMicFinish;  
  8.     private TextView txtMicAmplitudeMsg;  
  9.     private TextView txtMicTimeMsg;  
  10.       
  11.     private File recAudioFile;  
  12.     private MediaRecorder mMediaRecorder;  
  13.     private Resources res;  
  14.       
  15.     private static int time;  
  16.     private static int mic_state = MIC_STATE_RECORD;  
  17.       
  18.     private Thread threadAmplitude;  
  19.     private Thread threadTime;  
  20.     private static boolean threadRun ;  
  21.       
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.mic);  
  26.         setupViews();  
  27.     }  
  28.       
  29.     @Override  
  30.     protected void onPause() {  
  31.         super.onPause();  
  32.         threadAmplitude = null;  
  33.         threadTime = null;  
  34.           
  35.     }  
  36.       
  37.     private void setupViews() {  
  38.           
  39.           
  40.         btnMicRecord = (Button) findViewById(R.id.mic_record);  
  41.         btnMicPlay = (Button) findViewById(R.id.mic_play);  
  42.         btnMicFinish = (Button) findViewById(R.id.mic_finish);  
  43.         txtMicAmplitudeMsg = (TextView) findViewById(R.id.mic_amplitude_msg);  
  44.         txtMicTimeMsg = (TextView) findViewById(R.id.mic_time_msg);  
  45.           
  46.         btnMicRecord.setOnClickListener(this);  
  47.         btnMicPlay.setOnClickListener(this);  
  48.         btnMicFinish.setOnClickListener(this);  
  49.           
  50.         res = getResources();  
  51.         threadAmplitude = new Thread(new UpdateAmplitude());  
  52.         threadTime = new Thread(new UpdateTime());  
  53.     }  
  54.       
  55.       
  56.     //@Override   
  57.     public void onClick(View v) {  
  58.         switch (v.getId()) {  
  59.         case R.id.mic_record:  
  60.             if (mic_state== MIC_STATE_RECORD) { // 录音   
  61.                 btnMicRecord.setText(res.getString(R.string.mic_record_save_text));  
  62.                 mic_state = MIC_STATE_SAVE;  
  63.                 startRecorder();  
  64.             } else if (mic_state== MIC_STATE_SAVE) {  
  65.                 btnMicRecord.setText(res.getString(R.string.mic_record_text));  
  66.                 btnMicRecord.setEnabled(false);  
  67.                 btnMicPlay.setEnabled(true);  
  68.                 mic_state = MIC_STATE_RECORD;  
  69.                 stopRecorder();  
  70.             }  
  71.             break;  
  72.         case R.id.mic_play:  
  73.             openFile(recAudioFile);  
  74.             btnMicRecord.setEnabled(true);  
  75.             btnMicFinish.setEnabled(true);  
  76.             break;  
  77.         case R.id.mic_finish:  
  78.             new AlertDialog.Builder(MicActivity.this).setIcon(  
  79.                     R.drawable.icon).setTitle(res.getString(R.string.mic_title))  
  80.                     .setMessage(res.getString(R.string.mic_msg)).setPositiveButton(  
  81.                             res.getString(R.string.yes), dialogClick)  
  82.                     .setNegativeButton(res.getString(R.string.no), dialogClick).create().show();  
  83.             break;  
  84.         default:  
  85.             break;  
  86.         }  
  87.     }  
  88.       
  89.     private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() {  
  90.   
  91.         //@Override   
  92.         public void onClick(DialogInterface dialog, int which) {  
  93.             switch (which) {  
  94.             case DialogInterface.BUTTON_POSITIVE:  
  95.                 result(true);  
  96.                 break;  
  97.             case DialogInterface.BUTTON_NEGATIVE:  
  98.                 result(false);  
  99.                 break;  
  100.             default:  
  101.                 break;  
  102.             }  
  103.               
  104.   
  105.         }  
  106.     };  
  107.       
  108.       
  109.     private void result(boolean flag){  
  110.         Intent intent = new Intent(MicActivity.this, MainActivity.class);  
  111.         intent.putExtra(MIC_RESULT, flag);  
  112.         setResult(REQUESTCODE_MIC_RESULT, intent);  
  113.         finish();  
  114.     }  
  115.       
  116.     private class UpdateAmplitude implements Runnable{  
  117.   
  118.         //@Override   
  119.         public void run() {  
  120.             while (threadRun) {  
  121.                 try {  
  122.                     Message msg = new Message();  
  123.                     msg.what = mMediaRecorder.getMaxAmplitude();  
  124.                     amplitudeHandler.sendMessage(msg);  
  125.                     Thread.sleep(250);  
  126.                 } catch (InterruptedException e) {  
  127.                     e.printStackTrace();  
  128.                 }  
  129.             }  
  130.         }  
  131.     }  
  132.       
  133.     private Handler amplitudeHandler = new Handler(){  
  134.         @Override  
  135.         public void handleMessage(Message msg) {  
  136.             super.handleMessage(msg);  
  137.             String text = String.format(res.getString(R.string.mic_status_amplitude),String.valueOf(msg.what));  
  138.             txtMicAmplitudeMsg.setText(text);  
  139.         }  
  140.     };  
  141.       
  142.     private class UpdateTime implements Runnable{  
  143.         //@Override   
  144.         public void run() {  
  145.             while (threadRun) {  
  146.                 try {  
  147.                     Thread.sleep(1000);  
  148.                     time++;  
  149.                     timeHandler.sendEmptyMessage(time);  
  150.                 } catch (InterruptedException e) {  
  151.                     e.printStackTrace();  
  152.                 }  
  153.                   
  154.             }  
  155.         }  
  156.     }  
  157.       
  158.     private Handler timeHandler = new Handler(){  
  159.         public void handleMessage(Message msg) {  
  160.             super.handleMessage(msg);  
  161.             String text = String.format(res.getString(R.string.mic_status_time), String.valueOf(msg.what));  
  162.             txtMicTimeMsg.setText(text);  
  163.         };  
  164.     };  
  165.       
  166.     private void startRecorder(){  
  167.         mMediaRecorder = new MediaRecorder();  
  168.         recAudioFile = new File("/mnt/flash""new.amr");  
  169.         if (recAudioFile.exists()) {  
  170.             recAudioFile.delete();  
  171.         }  
  172.         mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置录音来源   
  173.         mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);  
  174.         mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);   
  175.         mMediaRecorder.setOutputFile(recAudioFile.getAbsolutePath());    
  176.           
  177.         try {  
  178.             mMediaRecorder.prepare();  
  179.         } catch (IllegalStateException e) {  
  180.             e.printStackTrace();  
  181.         } catch (IOException e) {  
  182.             e.printStackTrace();  
  183.         }  
  184.         mMediaRecorder.start();  
  185.         threadRun = true;  
  186.         threadAmplitude.start();  
  187.         threadTime.start();  
  188.     }  
  189.       
  190.     private void stopRecorder(){  
  191.         time = 0;  
  192.         threadRun = false;  
  193.         if (recAudioFile!=null) {  
  194.             mMediaRecorder.stop();  
  195.             mMediaRecorder.release();  
  196.         }  
  197.     }  
  198.   
  199.     /* 打开播放录音文件的程序 */  
  200.     private void openFile(File f) {  
  201.         Intent intent = new Intent();  
  202.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  203.         intent.setAction(android.content.Intent.ACTION_VIEW);  
  204.         String type = getMIMEType(f);  
  205.         intent.setDataAndType(Uri.fromFile(f), type);  
  206.         startActivity(intent);  
  207.     }  
  208.   
  209.     private String getMIMEType(File f) {  
  210.         String end = f.getName().substring(f.getName().lastIndexOf(".") + 1,  
  211.                 f.getName().length()).toLowerCase();  
  212.         String type = "";  
  213.         if (end.equals("mp3") || end.equals("aac") || end.equals("aac")  
  214.                 || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {  
  215.             type = "audio";  
  216.         } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")  
  217.                 || end.equals("jpeg")) {  
  218.             type = "image";  
  219.         } else {  
  220.             type = "*";  
  221.         }  
  222.         type += "/*";  
  223.         return type;  
  224.     }  
  225.       
  226. }  
public class MicActivity extends Activity implements OnClickListener{ private final static String TAG="MicActivity"; private Button btnMicRecord; private Button btnMicPlay; private Button btnMicFinish; private TextView txtMicAmplitudeMsg; private TextView txtMicTimeMsg; private File recAudioFile; private MediaRecorder mMediaRecorder; private Resources res; private static int time; private static int mic_state = MIC_STATE_RECORD; private Thread threadAmplitude; private Thread threadTime; private static boolean threadRun ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mic); setupViews(); } @Override protected void onPause() { super.onPause(); threadAmplitude = null; threadTime = null; } private void setupViews() { btnMicRecord = (Button) findViewById(R.id.mic_record); btnMicPlay = (Button) findViewById(R.id.mic_play); btnMicFinish = (Button) findViewById(R.id.mic_finish); txtMicAmplitudeMsg = (TextView) findViewById(R.id.mic_amplitude_msg); txtMicTimeMsg = (TextView) findViewById(R.id.mic_time_msg); btnMicRecord.setOnClickListener(this); btnMicPlay.setOnClickListener(this); btnMicFinish.setOnClickListener(this); res = getResources(); threadAmplitude = new Thread(new UpdateAmplitude()); threadTime = new Thread(new UpdateTime()); } //@Override public void onClick(View v) { switch (v.getId()) { case R.id.mic_record: if (mic_state== MIC_STATE_RECORD) { // 录音 btnMicRecord.setText(res.getString(R.string.mic_record_save_text)); mic_state = MIC_STATE_SAVE; startRecorder(); } else if (mic_state== MIC_STATE_SAVE) { btnMicRecord.setText(res.getString(R.string.mic_record_text)); btnMicRecord.setEnabled(false); btnMicPlay.setEnabled(true); mic_state = MIC_STATE_RECORD; stopRecorder(); } break; case R.id.mic_play: openFile(recAudioFile); btnMicRecord.setEnabled(true); btnMicFinish.setEnabled(true); break; case R.id.mic_finish: new AlertDialog.Builder(MicActivity.this).setIcon( R.drawable.icon).setTitle(res.getString(R.string.mic_title)) .setMessage(res.getString(R.string.mic_msg)).setPositiveButton( res.getString(R.string.yes), dialogClick) .setNegativeButton(res.getString(R.string.no), dialogClick).create().show(); break; default: break; } } private android.content.DialogInterface.OnClickListener dialogClick = new android.content.DialogInterface.OnClickListener() { //@Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: result(true); break; case DialogInterface.BUTTON_NEGATIVE: result(false); break; default: break; } } }; private void result(boolean flag){ Intent intent = new Intent(MicActivity.this, MainActivity.class); intent.putExtra(MIC_RESULT, flag); setResult(REQUESTCODE_MIC_RESULT, intent); finish(); } private class UpdateAmplitude implements Runnable{ //@Override public void run() { while (threadRun) { try { Message msg = new Message(); msg.what = mMediaRecorder.getMaxAmplitude(); amplitudeHandler.sendMessage(msg); Thread.sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } } } private Handler amplitudeHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); String text = String.format(res.getString(R.string.mic_status_amplitude),String.valueOf(msg.what)); txtMicAmplitudeMsg.setText(text); } }; private class UpdateTime implements Runnable{ //@Override public void run() { while (threadRun) { try { Thread.sleep(1000); time++; timeHandler.sendEmptyMessage(time); } catch (InterruptedException e) { e.printStackTrace(); } } } } private Handler timeHandler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); String text = String.format(res.getString(R.string.mic_status_time), String.valueOf(msg.what)); txtMicTimeMsg.setText(text); }; }; private void startRecorder(){ mMediaRecorder = new MediaRecorder(); recAudioFile = new File("/mnt/flash", "new.amr"); if (recAudioFile.exists()) { recAudioFile.delete(); } mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置录音来源 mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); mMediaRecorder.setOutputFile(recAudioFile.getAbsolutePath()); try { mMediaRecorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } mMediaRecorder.start(); threadRun = true; threadAmplitude.start(); threadTime.start(); } private void stopRecorder(){ time = 0; threadRun = false; if (recAudioFile!=null) { mMediaRecorder.stop(); mMediaRecorder.release(); } } /* 打开播放录音文件的程序 */ private void openFile(File f) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); String type = getMIMEType(f); intent.setDataAndType(Uri.fromFile(f), type); startActivity(intent); } private String getMIMEType(File f) { String end = f.getName().substring(f.getName().lastIndexOf(".") + 1, f.getName().length()).toLowerCase(); String type = ""; if (end.equals("mp3") || end.equals("aac") || end.equals("aac") || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) { type = "audio"; } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) { type = "image"; } else { type = "*"; } type += "/*"; return type; } }12、重力感应
view plain copy to clipboard print ?
  1. public class MySensorEventListener implements SensorEventListener {  
  2.   
  3.     private boolean isPass;  
  4.   
  5.     private SaveMessage saveMessage;  
  6.   
  7.     public MySensorEventListener(Context context) {  
  8.         saveMessage = new SaveMessage(context);  
  9.     }  
  10.   
  11.     // @Override   
  12.     public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  13.     }  
  14.   
  15.     // @Override   
  16.     public void onSensorChanged(SensorEvent event) {  
  17.         if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {  
  18.             // 得到方向的值   
  19.             float x = event.values[SensorManager.DATA_X];  
  20.             float y = event.values[SensorManager.DATA_Y];  
  21.             float z = event.values[SensorManager.DATA_Z];  
  22.             isPass = x != 0 || y != 0 || z != 0;  
  23.             System.out.println("Orientation-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!"));  
  24.             saveMessage.setMessage(MSG_SENEOR, "Orientation-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!"));  
  25.         } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {  
  26.             // 得到加速度的值   
  27.             float x = event.values[SensorManager.DATA_X];  
  28.             float y = event.values[SensorManager.DATA_Y];  
  29.             float z = event.values[SensorManager.DATA_Z];  
  30.             isPass = x != 0 || y != 0 || z != 0;  
  31.             System.out.println("Accelerometer-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!"));  
  32.             saveMessage.setMessage(MSG_SENEOR, "Accelerometer-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!"));  
  33.         }  
  34.     }  
  35.   
  36. }  
public class MySensorEventListener implements SensorEventListener { private boolean isPass; private SaveMessage saveMessage; public MySensorEventListener(Context context) { saveMessage = new SaveMessage(context); } // @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } // @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { // 得到方向的值 float x = event.values[SensorManager.DATA_X]; float y = event.values[SensorManager.DATA_Y]; float z = event.values[SensorManager.DATA_Z]; isPass = x != 0 || y != 0 || z != 0; System.out.println("Orientation-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!")); saveMessage.setMessage(MSG_SENEOR, "Orientation-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!")); } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { // 得到加速度的值 float x = event.values[SensorManager.DATA_X]; float y = event.values[SensorManager.DATA_Y]; float z = event.values[SensorManager.DATA_Z]; isPass = x != 0 || y != 0 || z != 0; System.out.println("Accelerometer-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!")); saveMessage.setMessage(MSG_SENEOR, "Accelerometer-Seneor " + (isPass ? "ok!" + " x=" + x + " y=" + y + " z=" + z : "error!")); } } }
原创文章,转载请注明出处: http://blog.csdn.net/tangcheng_ok/article/details/6684646

你可能感兴趣的:(android,网络,String,null,button,resources)