这篇文章主要是记录前段时间开发所用到的一些技术,在这里做个总结,文中有不足之处还请看到本文的你多多指点。分享分享开发经验,一起提高!
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
- boolean flag = false;
- lt;pre class="java" name="code"> BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter.isEnabled()) { bluetoothAdapter.disable(); flag =
bluetoothAdapter.enable(); } else { flag = bluetoothAdapter.enable(); }
3、电池
1、新建一个广播接收类
- 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() {
-
-
- 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() {
-
-
- 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();
- }
-
-
- 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(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);
-
- 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!");
- }
- }
-
-
- public void onStartTrackingTouch(SeekBar seekBar) {}
-
-
- 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
- };
- vibrator.vibrate(pattern, 2);
8、摄像头(拍照和预览)
- public class CameraActivity extends Activity{
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
- res = getResources();
- btnFinish =(Button) findViewById(R.id.camera_finish);
-
- btnFinish.setOnClickListener(new OnClickListener() {
-
-
- 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() {
-
-
- 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() {
-
- 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;
- }
- }
-
-
- SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
-
- public void surfaceCreated(SurfaceHolder holder) {
- camera = Camera.open();
- try {
- camera.setPreviewDisplay(holder);
- } catch (IOException e) {
- camera.release();
- camera = null;
- }
- }
-
-
- 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();
-
- }
-
-
- 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());
- }
-
-
-
- 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() {
-
-
- 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{
-
-
- 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{
-
- 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);
- }
-
-
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
-
-
- 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
|