ListView自定义背景后 滚动时背景变黑的问题
ListView是常用的显示控件,默认背景是和系统窗口一样的透明色,如果给ListView加上背景图片,或者背景颜色时,滚动时listView会黑掉,原因是,滚动时,列表里面的view重绘时,用的依旧是系统默认的透明色,颜色值为#FF191919,要改变这种情况,只需要调用 listView的setCacheColorHint(0),颜色值设置为0或者xml文件中listView的属性 android:cacheColorHint="#00000000"即可,滚动时,重绘View的时候就不会有背景颜色。
android 获取路径目录方法以及判断目录是否存在,创建目录
Environment 常用方法:
* 方法:getDataDirectory()
解释:返回 File ,获取 Android 数据目录。
* 方法:getDownloadCacheDirectory()
解释:返回 File ,获取 Android 下载/缓存内容目录。
* 方法:getExternalStorageDirectory()
解释:返回 File ,获取外部存储目录即 SDCard
* 方法:getExternalStoragePublicDirectory(String type)
解释:返回 File ,取一个高端的公用的外部存储器目录来摆放某些类型的文件
* 方法:getExternalStorageState()
解释:返回 File ,获取外部存储设备的当前状态
* 方法:getRootDirectory()
解释:返回 File ,获取 Android 的根目录
public void getSDPath(){
File sdDir = null;
File sdDir1 = null;
File sdDir2 = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
if (sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
sdDir1 = Environment.getDataDirectory();
sdDir2 =Environment.getRootDirectory();
}
System.out.println("getExternalStorageDirectory(): "+sdDir.toString());
System.out.println("getDataDirectory(): "+sdDir1.toString());
System.out.println("getRootDirectory(): "+sdDir2.toString());
}
//判断一个路径下的文件(文件夹)是否存在
public class IsExist {
public static void main(String[] args) {
isExist("e://12");
}
/**
*
* @param path 文件夹路径
*/
public static void isExist(String path) {
File file = new File(path);
//判断文件夹是否存在,如果不存在则创建文件夹
if (!file.exists()) {
file.mkdir();
}
}
}
1.在SD卡上创建一个文件夹
public class make extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File sd=Environment.getExternalStorageDirectory();
String path=sd.getPath()+"/notes";
File file=new File(path);
if(!file.exists())
file.mkdir();
}
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三点坐标的值)
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; - lt;pre
class="java" name="code"> 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.setOnSeekBarChangeListen er(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.getExternalStorageDirect ory().getPath(); - }
-
- static
boolean checkSdcard(){ -
boolean flag = false; -
if(Environment.getExternalStorageDirect ory().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.getExternalStorageDirect ory(), -
"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即可)
- @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 += " 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