Android开发之--WIFI,蓝牙,电池,背光,SD卡,摄像头,按键,MIC,重力感应等各种操作

原创 2011年08月13日 22:41:14

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

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

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、蓝牙

        boolean flag = false;
       
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); flag = bluetoothAdapter.enable(); } else { flag = bluetoothAdapter.enable(); }

3、电池

1、新建一个广播接收类

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、注册广播

IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, intentFilter);

4、背光

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的路径

	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、振动马达

 vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        long[] pattern = {
                800, 50, 400, 30
        }; // OFF/ON/OFF/ON...
        vibrator.vibrate(pattern, 2);

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

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键的方法:
@Override
	public void onAttachedToWindow() {
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);   
	    super.onAttachedToWindow(); 	
	}

10、音乐播放器

11、录音

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、重力感应
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


                

第62篇 摄像头屏蔽(二)

关键词:摄像头屏蔽  一、摄像头屏蔽 1.1 部署在14服务器 用原版: 老师端:https://192.168.1.14:9001/  (需要用open打开) 学生端:https://19...
  • SanBaDao
  • SanBaDao
  • 2017年01月19日 16:30
  • 298

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

http://blog.csdn.net/tangcheng_ok/article/details/6684646     这篇文章主要是记录前段时间开发所用到的一些技术,在这里做个...
  • gaoguoxin2
  • gaoguoxin2
  • 2012年12月17日 10:15
  • 1373

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

http://blog.csdn.net/tangcheng_ok/article/details/6684646 这篇文章主要是记录前段时间开发所用到的一些技术,在这里做个总结,文中有不足之处...
  • lsr693120
  • lsr693120
  • 2015年03月27日 16:42
  • 368

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

1、WIFI(打开,关闭,使能,扫描等) 2、蓝牙(打开关闭) 3、电池(获取电池的各种参数和状态信息) 4、背光(背光调节) 5、U盘/SDcard(判断是否插入,读取等) 6、屏幕校准(...
  • qeqeqe236
  • qeqeqe236
  • 2011年11月28日 17:09
  • 1682

Android开发之--WIFI,蓝牙,电池,背光,SD卡,摄像头,按键,MIC,重力感应等各种操作

这篇文章主要是记录前段时间开发所用到的一些技术,在这里做个总结,文中有不足之处还请看到本文的你多多指点。分享分享开发经验,一起提高! 1、WIFI(打开,关闭,使能,扫描等) 2、蓝牙(打开关闭) ...
  • tangcheng_ok
  • tangcheng_ok
  • 2011年08月13日 22:41
  • 10471

Android资源下载

Android 上百实例源码分析以及开源分析 集合打包7
  • u010461658
  • u010461658
  • 2014年10月23日 19:43
  • 1927

摄像头和SD卡(一)

摄像头+SD卡综述:      《STM32F407开发指南-寄存器版本》:       OV7640的寄存器通过SCCB时序访问并设置,SCCB时序和IIC时序十分类似。       OV7...
  • liuwei423210896
  • liuwei423210896
  • 2015年08月05日 09:29
  • 1008

无线SD卡Eye-Fi大拆解

转载至:http://www.you01.com/dzly/html/80/n-5680.html 去年曾经就给大家介绍过Eye-Fi 。今天为大家介绍一下Eye-Fi的内部到底都有些什么东西,...
  • robertsong2004
  • robertsong2004
  • 2014年09月01日 13:27
  • 2108

第64篇 摄像头屏蔽(四)及运行官网音频代码

关键词:摄像头屏蔽, 运行官网音频代码 一、摄像头屏蔽 1.1 在下载的音频官网源码中 找到了一个demo,是控制摄像头的,如下: 1.2 先看官网demo,如下: https://...
  • SanBaDao
  • SanBaDao
  • 2017年01月20日 07:35
  • 248

Android framework系统默认设置修改

Launcher 总结:   1、launcher的布局太居中,要想两边拉伸     apps_customize_pageLayoutPaddingLeft">40dp     ap...
  • wh_19910525
  • wh_19910525
  • 2014年10月29日 10:23
  • 6037
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android开发之--WIFI,蓝牙,电池,背光,SD卡,摄像头,按键,MIC,重力感应等各种操作
举报原因:
原因补充:

(最多只允许输入30个字)