- public void showBluetoothCheckDialog(final Context context) {
- dialog = new AlertDialog.Builder(context).create();// 创建一个AlertDialog对象viewReconnectBluetooth = ((Activity) context).getLayoutInflater().inflate(R.layout.dialog_confirm_bluetooth, null);// 自定义布局messagetext = (TextView) viewReconnectBluetooth.findViewById(R.id.message);dialog.setCancelable(false);// dialog弹出后会点击屏幕或物理返回键,dialog不消失messagetext.setText("当前是蓝牙模式,但是蓝牙设备已断开连接,请选择操作。");View reconnect = viewReconnectBluetooth.findViewById(R.id.reconnect);reconnect.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(context,
- DeviceListActivity.class);context.startActivity(intent);dialog.dismiss();}
- });View cancel = viewReconnectBluetooth.findViewById(R.id.cancel);cancel.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // nothing to do
- dialog.dismiss();}
- });View shutdown = viewReconnectBluetooth.findViewById(R.id.shutdown);shutdown.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // Auto-generated method stub
- Util.savePreferences(Constants.BLUE_TOOTH,0, context);bluetoothAdapter.disable();app.setVersion(app.getVersion() +1);dialog.dismiss();Toast.makeText(context,"蓝牙模式已关闭", Toast.LENGTH_SHORT).show();}
- });dialog.setView(viewReconnectBluetooth,0,0,0,0);// 把自定义的布局设置到dialog中,注意,布局设置一定要在show之前。从第二个参数分别填充内容与边框之间左、上、右、下、的像素// Service&Application弹出对话框或WindowManager添加view时,要设置window type为TYPE_SYSTEM_ALERT
- dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);dialog.show();// 一定要先show出来再设置dialog的参数,不然就不会改变dialog的大小了}
MediaStore.Images.Media.getBitmap(ContentResolver cr,Uri url) 方法可以从一个已知的图片 Uri 中获得图片的 bitmap 对象,其中 ContentResolver 通常可以通过在 Activity 中调用的 getContentResolver() 方法中获取。Uri 地址就是类似 content://media/external/images/media/2 的地址,也就是 Content Provider 定义的地址形式。但是这种获取 bitmap 的方式在图片较大的时候并不可取。为什么呢?
从 getBitmap 的参数可以看出,我们没有传递所要得到的 bitmap 大小信息,那么 getBitmap 的返回的 bitmap 究竟有多大我们就无从知晓,完全取决于 getBitmap 本身,最乐观的结果是 getBitmap 能智能的判断我们的需求,返回一个合适的 bitmap,但是可能性很小。到底 getBitmap 中做了什么还是直接去看他的实现源码吧:
android.provider.MediaStore 中找到 Images.Media 的 getBitmap 方法:
- public static finalBitmapgetBitmap(ContentResolver cr, Uri url)throwsFileNotFoundException, IOException {
- InputStream input = cr.openInputStream(url);
- Bitmap bitmap = BitmapFactory.decodeStream(input);
- input.close();returnbitmap;
- }
其实它很简单很粗暴,返回的是原始大小的 bitmap。
MediaStore.Images.Media 自身的 getBitmap 不是很可靠。那我们来自定义一个 getBitmap 吧:
取名叫 getThumbnail,他能返回一个指定大小的 bitmap:
- public staticBitmapgetThumbnail(Uri uri,intsize)throwsFileNotFoundException, IOException{
- InputStream input =this.getContentResolver().openInputStream(uri);
- BitmapFactory.Options onlyBoundsOptions =newBitmapFactory.Options();
- onlyBoundsOptions.inJustDecodeBounds =true;
- onlyBoundsOptions.inDither=true;//optionalonlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optionalBitmapFactory.decodeStream(input,null, onlyBoundsOptions);
- input.close();if((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))return null;intoriginalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;doubleratio = (originalSize > size) ? (originalSize / size) :1.0;
- BitmapFactory.Options bitmapOptions =newBitmapFactory.Options();
- bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
- bitmapOptions.inDither=true;//optionalbitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optionalinput =this.getContentResolver().openInputStream(uri);
- Bitmap bitmap = BitmapFactory.decodeStream(input,null, bitmapOptions);
- input.close();returnbitmap;
- }private static int getPowerOfTwoForSampleRatio(doubleratio){intk = Integer.highestOneBit((int)Math.floor(ratio));if(k==0)return 1;else returnk;
- }
- private String getPath(Uri uri) {
- String[] projection = {
- MediaStore.Video.Media.DATA
- };
- Cursor cursor = managedQuery(uri, projection, null, null, null);
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
- cursor.moveToFirst();
- return cursor.getString(column_index);
- }
- Uri uri = Uri.parse(path);
- Stringpath =file.getPath()
- File file=new File(path)
- /**
- * 将图片Bitmap保存到本地返回File
- * @parambmp
- */
- publicFilesaveBmpToFile(Bitmap bmp) {// 将图片保存到本地时进行压缩开始时间Log.v("TakePhoteActivity.this","将图片保存到本地时进行压缩开始时间"+getTime());
- ByteArrayOutputStream baos =newByteArrayOutputStream();intoptions =100;
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 系统时间
- longdateTaken = System.currentTimeMillis();
- SimpleDateFormat formatter =newSimpleDateFormat("yyyy-MM-dd HH.mm.ss.SSS");
- String formatStr =formatter.format(dateTaken);// 图像名称String filename = formatStr +".JPEG";
- File parent =newFile(PATH);if(!parent.exists()) {
- parent.mkdirs();
- }
- File file =newFile(PATH, filename);if(file.exists()){
- file.delete();
- }try{
- FileOutputStream fos =newFileOutputStream(file);
- fos.write(baos.toByteArray());
- fos.flush();
- fos.close();
- }catch(Exception e) {
- e.printStackTrace();
- }returnfile;
- }
- /**
- * 存储图像并将信息添加入媒体数据库
- */private Uri insertImage(ContentResolver cr, String name, long dateTaken,
- String directory, String filename, Bitmap source, byte[] jpegData) {
- OutputStream outputStream = null;String filePath = directory + filename;try {
- File dir = new File(directory);if (!dir.exists()) {
- dir.mkdirs();}
- File file = new File(directory, filename);if (file.createNewFile()) {
- outputStream = new FileOutputStream(file);if (source != null) {
- source.compress(Bitmap.CompressFormat.JPEG,100, outputStream);} else {
- outputStream.write(jpegData);}
- }
- } catch (FileNotFoundException e) {
- Log.e(TAG, e.getMessage());return null;} catch (IOException e) {
- Log.e(TAG, e.getMessage());return null;} finally {
- if (outputStream != null) {
- try {
- outputStream.close();} catch (Throwable t) {
- }
- }
- }
- try {
- ContentValues values = new ContentValues(7);values.put(MediaStore.Images.Media.TITLE, name);values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);values.put(MediaStore.Images.Media.MIME_TYPE,"image/JPEG");values.put(MediaStore.Images.Media.DATA, filePath);return cr.insert(IMAGE_URI, values);} catch (Exception e) {/**
- * @Description: 用户禁用了下载服务时,通过如下代码进入"启用/禁用"下载管理程序界面
- * @Author: BG235144/AMOSCXY
- * @Data 2017/3/2 15:34
- */String packageName ="com.android.providers.downloads";Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);intent.setData(Uri.parse("package:"+ packageName));startActivity(intent);Toast.makeText(TakePhoteActivity.this,"请开启下载服务!", Toast.LENGTH_SHORT).show();ContentValues values = new ContentValues(7);values.put(MediaStore.Images.Media.TITLE, name);values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);values.put(MediaStore.Images.Media.MIME_TYPE,"image/JPEG");values.put(MediaStore.Images.Media.DATA, filePath);return cr.insert(IMAGE_URI, values);}
- }
- // 图片存储路径
- public static finalString PATH = Environment.getExternalStorageDirectory()
- .toString() +"/AndroidMedia/";// 系统时间
- longdateTaken = System.currentTimeMillis();
- SimpleDateFormat formatter =newSimpleDateFormat("yyyy-MM-dd HH.mm.ss.SSS");
- String formatStr = formatter.format(dateTaken);// 图像名称String filename = formatStr +".JPEG";byte[] jpegData = Bitmap2Bytes(bitmap);// 保存图片Uri uri = insertImage(getContentResolver(), filename, dateTaken, PATH, bitmap, jpegData);/**
- * Bitmap → byte[]
- * @parambm
- * @return*/
- public byte[]Bitmap2Bytes(Bitmap bm) {
- ByteArrayOutputStream baos =newByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.PNG,100, baos);returnbaos.toByteArray();
- }
- Bitmap bt = BitmapFactory.decodeFile(file.getPath()); //图片地址
- Bitmap mBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
- Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,null));
- privateBitmapzoomImage(Bitmap bm,intnewWidth,intnewHeight){// 获得图片的宽高
- intwidth = bm.getWidth()intheight = bm.getHeight();// 计算缩放比例
- floatscaleWidth = ((float) newWidth) / width;floatscaleHeight = ((float) newHeight) / height;// 取得想要缩放的matrix参数Matrix matrix =newMatrix();
- matrix.postScale(scaleWidth, scaleHeight);// 得到新的图片Bitmap newbm = Bitmap.createBitmap(bm,0,0, width, height, matrix,true);returnnewbm;
- }
- privateBitmapcomp(Bitmap image) {
- Matrix matrix =newMatrix();
- Bitmap bitmap = image;while(bitmap.getWidth() >512|| bitmap.getHeight() >1024) {
- matrix.setScale(0.9f,0.9f);
- bitmap = Bitmap.createBitmap(bitmap,0,0, bitmap.getWidth(), bitmap.getHeight(), matrix,true);
- }returnbitmap;
- }
- /**
- * 将图片保存到本地时进行压缩
- *
- * @parambmp
- */
- publicBitmapcompressBmpToFile(Bitmap bmp) {
- ByteArrayOutputStream baos =newByteArrayOutputStream();intoptions =60;
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);// 系统时间
- longdateTaken = System.currentTimeMillis();
- SimpleDateFormat formatter =newSimpleDateFormat("yyyy-MM-dd HH.mm.ss.SSS");
- String formatStr = formatter.format(dateTaken);// 图像名称String filename = formatStr +".JPEG";
- File parent =newFile(PATH);if(!parent.exists()) {
- parent.mkdirs();
- }
- File file =newFile(PATH, filename);if(file.exists()) {
- file.delete();
- }try{
- FileOutputStream fos =newFileOutputStream(file);
- fos.write(baos.toByteArray());
- fos.flush();
- fos.close();
- }catch(Exception e) {
- e.printStackTrace();
- }
- String filePath = PATH + filename;
- Bitmap scanBitmap = BitmapFactory.decodeFile(filePath);returnscanBitmap;
- }
- /**
- * 将图片保存到本地时进行压缩
- * @parambmp
- */
- publicBitmapcompressBmpToFile(Bitmap bmp){
- ByteArrayOutputStream baos =newByteArrayOutputStream();intoptions =80;//个人喜欢从80开始,bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);while(baos.toByteArray().length /1024>50) {
- baos.reset();
- options -=5;
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
- }// 系统时间
- longdateTaken = System.currentTimeMillis();// 图像名称String filename = DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken)
- .toString() +".jpg";
- File file =newFile(PATH, filename);try{
- FileOutputStream fos =newFileOutputStream(file);
- fos.write(baos.toByteArray());
- fos.flush();
- fos.close();
- }catch(Exception e) {
- e.printStackTrace();
- }
- String filePath=PATH + filename;
- Bitmap bitmap=BitmapFactory.decodeFile(filePath);returnbitmap;
- }
Curzibn/Luban
- private byte[]Bitmap2Bytes(Bitmap bm){
- ByteArrayOutputStream baos =newByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.PNG,100, baos);returnbaos.toByteArray();
- }
- privateBitmapBytes2Bimap(byte[] b){if(b.length!=0){returnBitmapFactory.decodeByteArray(b,0, b.length);
- }else{return null;
- }
- }
- Resources res=getResources();Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
- public static final intCHOOSE_PHOTO =2;
- Button chooseFromAlbum.setOnClickListener(newView.OnClickListener() {@Override
- public void onClick(View v) {if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(MainActivity.this,newString[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE },1);
- }else{
- openAlbum();
- }
- }
- });private void openAlbum() {
- Intent intent =newIntent("android.intent.action.GET_CONTENT");
- intent.setType("image/*");
- startActivityForResult(intent, CHOOSE_PHOTO);// 打开相册}@Override
- public void onRequestPermissionsResult(intrequestCode, String[] permissions,int[] grantResults) {switch(requestCode) {case 1:if(grantResults.length >0&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- openAlbum();
- }else{
- Toast.makeText(this,"权限被拒绝", Toast.LENGTH_SHORT).show();
- }break;default:
- }
- }@Override
- protected void onActivityResult(intrequestCode,intresultCode, Intent data) {switch(requestCode) {caseCHOOSE_PHOTO:if(resultCode == RESULT_OK) {// 判断手机系统版本号
- if(Build.VERSION.SDK_INT >=19) {// 4.4及以上系统使用这个方法处理图片handleImageOnKitKat(data);
- }else{// 4.4以下系统使用这个方法处理图片handleImageBeforeKitKat(data);
- }
- }break;default:break;
- }
- }@TargetApi(19)private void handleImageOnKitKat(Intent data) {
- String imagePath =null;
- Uri uri = data.getData();
- Log.d("TAG","handleImageOnKitKat: uri is "+ uri);if(DocumentsContract.isDocumentUri(this, uri)) {// 如果是document类型的Uri,则通过document id处理String docId = DocumentsContract.getDocumentId(uri);if("com.android.providers.media.documents".equals(uri.getAuthority())) {
- String id = docId.split(":")[1];// 解析出数字格式的idString selection = MediaStore.Images.Media._ID +"="+ id;
- imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
- }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
- Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
- imagePath = getImagePath(contentUri,null);
- }
- }else if("content".equalsIgnoreCase(uri.getScheme())) {// 如果是content类型的Uri,则使用普通方式处理imagePath = getImagePath(uri,null);
- }else if("file".equalsIgnoreCase(uri.getScheme())) {// 如果是file类型的Uri,直接获取图片路径即可imagePath = uri.getPath();
- }
- displayImage(imagePath);// 根据图片路径显示图片}private void handleImageBeforeKitKat(Intent data) {
- Uri uri = data.getData();
- String imagePath = getImagePath(uri,null);
- displayImage(imagePath);
- }privateStringgetImagePath(Uri uri, String selection) {
- String path =null;// 通过Uri和selection来获取真实的图片路径Cursor cursor = getContentResolver().query(uri,null, selection,null,null);if(cursor !=null) {if(cursor.moveToFirst()) {
- path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
- }
- cursor.close();
- }returnpath;
- }private void displayImage(String imagePath) {if(imagePath !=null) {
- Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
- ImageView picture.setImageBitmap(bitmap);
- }else{
- Toast.makeText(this,"获取图片失败", Toast.LENGTH_SHORT).show();
- }
- }
- /**
- * @Class: NotificationsUtils
- * @Description:
- * @author: BG235144/AMOSCXY
- * @Date: 2017/3/13
- */
- public class NotificationsUtils{
- private static finalString CHECK_OP_NO_THROW ="checkOpNoThrow";private static finalString OP_POST_NOTIFICATION ="OP_POST_NOTIFICATION";@SuppressLint("NewApi")public static boolean isNotificationEnabled(Context context) {
- AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
- ApplicationInfo appInfo = context.getApplicationInfo();
- String pkg = context.getApplicationContext().getPackageName();intuid = appInfo.uid;
- Class appOpsClass =null;/* Context.APP_OPS_MANAGER */
- try{
- appOpsClass = Class.forName(AppOpsManager.class.getName());
- Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
- String.class);
- Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);intvalue = (Integer) opPostNotificationValue.get(Integer.class);return((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
- }catch(ClassNotFoundException e) {
- e.printStackTrace();
- }catch(NoSuchMethodException e) {
- e.printStackTrace();
- }catch(NoSuchFieldException e) {
- e.printStackTrace();
- }catch(InvocationTargetException e) {
- e.printStackTrace();
- }catch(IllegalAccessException e) {
- e.printStackTrace();
- }return false;
- }
- }
注意:Build.VERSION.SDK_INT>=19 时才能使用
- Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");String pkg ="com.android.settings";Stringcls="com.android.settings.applications.InstalledAppDetails";intent.setComponent(new ComponentName(pkg,cls));intent.setData(Uri.parse("package:"+ mContext.getPackageName()));startActivity(intent);
权限组名 | 权限名 |
---|---|
CALENDAR | READ_CALENDAR 、WRITE_CALENDAR |
CAMERA | CAMERA |
CONTACTS | READ_CONTACTS 、WRITE_CONTACTS、 GET_ACCOUNTS |
LOCATION | ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION |
MICROPHONE | RECORD_AUDIO |
PHONE | READ_PHONE_STATE、CALL_PHONE、READ_CALL_LOG、WRITE_CALL_LOG、ADD_VOICEMAIL、USE_SIP、PROCESS_OUTGOING_CALLS |
SENSOPS | BODY_SENSORS |
SMS | SEND_SMS、RECEIVE_SMS、READ_SMS、RECEIVE_WAP_PUSH、RECEIVE_SMS |
STORAGE | READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE |
- if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(MainActivity.this, new String[] {
- Manifest.permission.WRITE_EXTERNAL_STORAGE
- },
- 1);
- } else {
- // 获取权限后要执行的事件
- openAlbum();
- }
- // 检测到还没有获取到权限时执行,申请获取权限
- @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- switch (requestCode) {
- case 1:
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- // 获取权限后要执行的事件
- openAlbum();
- } else {
- Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
- }
- break;
- default:
- }
- }
- String callingApp = context.getPackageManager().getNameForUid(Binder.getCallingUid());
- PackageManager pm = this.getPackageManager();String appName = getApplicationInfo().loadLabel(pm).toString();
- privateStringgetAppInfo() {try{
- String pkName =this.getPackageName();
- String versionName =this.getPackageManager().getPackageInfo(
- pkName,0).versionName;intversionCode =this.getPackageManager()
- .getPackageInfo(pkName,0).versionCode;returnpkName +" "+ versionName +" "+ versionCode;
- }catch(Exception e) {
- }return null;
- }
- String systemVersion = android.os.Build.VERSION.RELEASE;
就是 Activity 的一个容器集合,所有的 Activity 实例都是存放在这个容器栈里面。其实就是数据结构中栈是一个原理:先进后出,后进先出,所有操作都是发生在栈顶。
launchMode 在多个 Activity 跳转的过程中扮演着重要的角色,它可以决定是否生成新的 Activity 实例,是否重用已存在的 Activity 实例,是否和其他 Activity 实例公用一个 task 里
- android:launchMode="standard"
默认启动模式,每次激活 Activity 时都会创建 Activity,并放入任务栈中。
如果在任务的栈顶正好存在该 Activity 的实例, 就重用该实例,否者就会创建新的实例并放入栈顶 (即使栈中已经存在该 Activity 实例,只要不在栈顶,都会创建实例)。
如果在栈中已经有该 Activity 的实例,就重用该实例 (会调用实例的 onNewIntent())。重用时,会让该实例回到栈顶,因此在它上面的实例将会被移除栈。如果栈中不存在该实例,将会创建新的实例放入栈中。
在一个新栈中创建该 Activity 实例,并让多个应用共享改栈中的该 Activity 实例。一旦改模式的 Activity 的实例存在于某个栈中,任何应用再激活改 Activity 时都会重用该栈中的实例,其效果相当于多个应用程序共享一个应用,不管谁激活该 Activity 都会进入同一个应用中。
大家遇到一个应用的 Activity 供多种方式调用启动的情况,多个调用希望只有一个 Activity 的实例存在,这就需要 Activity 的 onNewIntent(Intent intent) 方法了。只要在 Activity 中加入自己的 onNewIntent(intent) 的实现加上 Manifest 中对 Activity 设置 lanuchMode="singleTask" 就可以。
onNewIntent()非
来源: http://blog.csdn.net/amoscxy/article/details/72357900