欢迎使用CSDN-markdown编辑器
来源:互联网 发布:淘宝最火的网店 编辑:程序博客网 时间:2024/05/18 09:11
ClipboardService
1.复制数据到剪切板
public void copyDataToClipBoard(){ ClipBoardManager mgr = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); myClipboard.setPrimaryClip(ClipData.newUri(getContentResolver(),"Note", noteUri);}
- ClipData对象可以采取三种形式用于创建数据:
- Text
- newPlainText(label, text)
- 返回ClipData对象,其单个ClipData.Item对象包含一个文本字符串
2. URI - newUri(resolver, label, URI)
- 返回ClipData对象,其单ClipData.Item对象包含一个URI
3. Intent - newIntent(label, intent)
- 返回ClipData对象,其单ClipData.Item对象包含意图
// 用于获取剪切板制定的数据类型 static public ClipData newUri(ContentResolver resolver, CharSequence label, Uri uri) { Item item = new Item(uri); String[] mimeTypes = null; // 获取这个Uri所代表的数据类型,先尝试利用ContentResolver 查询,如果查询不到,将mimeTypes设置为 //ClipDescription.MIMETYPE_TEXT_URILIST if ("content".equals(uri.getScheme())) { String realType = resolver.getType(uri); mimeTypes = resolver.getStreamTypes(uri, "*/*"); if (mimeTypes == null) { if (realType != null) { mimeTypes = new String[] { realType, ClipDescription.MIMETYPE_TEXT_URILIST }; } } else { String[] tmp = new String[mimeTypes.length + (realType != null ? 2 : 1)]; int i = 0; if (realType != null) { tmp[0] = realType; i++; } System.arraycopy(mimeTypes, 0, tmp, i, mimeTypes.length); tmp[i + mimeTypes.length] = ClipDescription.MIMETYPE_TEXT_URILIST; mimeTypes = tmp; } } if (mimeTypes == null) { mimeTypes = MIMETYPES_TEXT_URILIST; } return new ClipData(label, mimeTypes, item); }
将数据传递到 ClipManagerService(–>ClipboardManager.java::setPrimaryClip)
/** * Sets the current primary clip on the clipboard. This is the clip that * is involved in normal cut and paste operations. * * @param clip The clipped data item to set. */ public void setPrimaryClip(ClipData clip) { try { if (clip != null) { clip.prepareToLeaveProcess(); } getService().setPrimaryClip(clip, mContext.getOpPackageName()); } catch (RemoteException e) { } }
ClipboardManagerService 完成实际的功能
public void setPrimaryClip(ClipData clip, String callingPackage) { synchronized (this) { // ... // todo 权限检查,稍后分析 checkDataOwnerLocked(clip, callingUid); final int userId = UserHandle.getUserId(callingUid); PerUserClipboard clipboard = getClipboard(userId); revokeUris(clipboard); // 保存新的clipData 到 mprimaryClip中,同时向监控剪切板的客户端发送通知 setPrimaryClipInternal(clipboard, clip); } }
/** 保存新的clipData 到 mprimaryClip中,同时向监控剪切板的客户端发送通知* 客户端通过addPrimaryClipChanageedListener函数注册回调*/void setPrimaryClipInternal(PerUserClipboard clipboard, ClipData clip) { clipboard.activePermissionOwners.clear(); if (clip == null && clipboard.primaryClip == null) { return; } clipboard.primaryClip = clip; final long ident = Binder.clearCallingIdentity(); final int n = clipboard.primaryClipListeners.beginBroadcast(); try { for (int i = 0; i < n; i++) { try { ListenerInfo li = (ListenerInfo) clipboard.primaryClipListeners.getBroadcastCookie(i); if (mAppOps.checkOpNoThrow(AppOpsManager.OP_READ_CLIPBOARD, li.mUid, li.mPackageName) == AppOpsManager.MODE_ALLOWED) { clipboard.primaryClipListeners.getBroadcastItem(i) .dispatchPrimaryClipChanged(); } } catch (RemoteException e) { // The RemoteCallbackList will take care of removing // the dead object for us. } } } finally { clipboard.primaryClipListeners.finishBroadcast(); Binder.restoreCallingIdentity(ident); } }
2.从剪切板粘贴数据
public void parseDataFromClipboard(Context context){ ClipBoardManager mgr = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE); // 这个方法是通过ClipboardManagerService 的getPrimaryClip()方法获取剪切板数据 ClipData clip = clipboard.getPrimaryClip(); ContentResolover cr = getContentResolover(); if(clip != null){ String text = null; ClipData.Item item = abc.getItemAt(0); Uri uri = item.getUri(); Cursor orig = cr.query(uri, PROJECTION, null, null, null); // ... 查询数据库并获取信息 orig.close(); if(text == null){ // 如果paste方不了解clipData中的数据类型,可调用该方法强制得到文本型数据 text = item.coerceToText(context).toString(); } }}
–> ClipboardManagerService.java::getPrimaryClip()
public ClipData getPrimaryClip(String pkg) { synchronized (this) { if (mAppOps.noteOp(AppOpsManager.OP_READ_CLIPBOARD, Binder.getCallingUid(), pkg) != AppOpsManager.MODE_ALLOWED) { return null; } // todo 赋予该包相应的权限,稍后分析 addActiveOwnerLocked(Binder.getCallingUid(), pkg); return getClipboard().primaryClip; } }
–> ClipData.java::coerceToText()
public CharSequence coerceToText(Context context) { // 如果该item已经有mText,则直接返回 CharSequence text = getText(); if (text != null) { return text; } // 如果是Uri类型数据 Uri uri = getUri(); if (uri != null) { // ContentProvider 需要实现 openTypedAssetFileDescriptor函数, // 以返回制定MIME类型的数据源 // FileInputStream stream = null; try { // Ask for a stream of the desired type. AssetFileDescriptor descr = context.getContentResolver() .openTypedAssetFileDescriptor(uri, "text/*", null); //创建一个输入流 stream = descr.createInputStream(); //创建一个InputStreamReader,读出来的数据转换成UTF8的文本 InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); // Got it... copy the stream into a local string and return it. StringBuilder builder = new StringBuilder(128); char[] buffer = new char[8192]; int len; //从ContentProvider那读取数据,然后转化成utf-8字符串 while ((len=reader.read(buffer)) > 0) { builder.append(buffer, 0, len); } return builder.toString(); } catch (FileNotFoundException e) { // Unable to open content URI as text... not really an // error, just something to ignore. } catch (IOException e) { // Something bad has happened. Log.w("ClippedData", "Failure loading text", e); return e.toString(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } // If we couldn't open the URI as a stream, then the URI itself // probably serves fairly well as a textual representation. return uri.toString(); } // Finally, if all we have is an Intent, then we can just turn that // into text. Not the most user-friendly thing, but it's something. Intent intent = getIntent(); if (intent != null) { return intent.toUri(Intent.URI_INTENT_SCHEME); } // Shouldn't get here, but just in case... return ""; }
- 3.权限检查
Android 系统的权限管理是专门针对URI的,例如我们在应用开发的时候需要往sdcard读写数据,我们需要在AndroidMainfest.xml文件中申请对应的权限,当我们实际进行读取数据时,系统会判断我们是否拥有权限,如果没有则会抛出异常.下面分析一下我们之前没有分析的权限检查.
- 复制数据时,权限检查函数:
- 为每一个Item调用checkItemOwnerLocked
- –> ClipboardSrvice.java::checkDataOwnerLocked
- –> ClipboardSrvice.java::checkItemOwnerLocked
private final void checkItemOwnerLocked(ClipData.Item item, int uid) { if (item.getUri() != null) { checkUriOwnerLocked(item.getUri(), uid); } Intent intent = item.getIntent(); if (intent != null && intent.getData() != null) { checkUriOwnerLocked(intent.getData(), uid); } }
private final void checkUriOwnerLocked(Uri uri, int uid) { if (!"content".equals(uri.getScheme())) { return; } long ident = Binder.clearCallingIdentity(); try { // 调用ActivityManagerService的checkGrantUriPermission函数 // 该函数内博检查copy方是否被赋予 URI_READ权限,如果没有则抛出异常 mAm.checkGrantUriPermission(uid, null, ContentProvider.getUriWithoutUserId(uri), Intent.FLAG_GRANT_READ_URI_PERMISSION, ContentProvider.getUserIdFromUri(uri, UserHandle.getUserId(uid))); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(ident); } }
- 粘贴方权限检查
- –>ClipboardService.java::addActiveOwnerLocked
private final void addActiveOwnerLocked(int uid, String pkg) { /*调用PackageManagerService的getPackagerInfo函数得到相关信息, 校验PackagerInfo中的uid信息与当前调用的uid是否一致,如果不一致则抛出异常 */ final IPackageManager pm = AppGlobals.getPackageManager(); final int targetUserHandle = UserHandle.getCallingUserId(); final long oldIdentity = Binder.clearCallingIdentity(); try { PackageInfo pi = pm.getPackageInfo(pkg, 0, targetUserHandle); if (pi == null) { throw new IllegalArgumentException("Unknown package " + pkg); } if (!UserHandle.isSameApp(pi.applicationInfo.uid, uid)) { throw new SecurityException("Calling uid " + uid + " does not own package " + pkg); } } catch (RemoteException e) { // Can't happen; the package manager is in the same process } finally { Binder.restoreCallingIdentity(oldIdentity); } // clipboard.activePermissionOwners用来保存已经通过安全检查的package PerUserClipboard clipboard = getClipboard(); if (clipboard.primaryClip != null && !clipboard.activePermissionOwners.contains(pkg)) { final int N = clipboard.primaryClip.getItemCount(); for (int i=0; i<N; i++) { grantItemLocked(clipboard.primaryClip.getItemAt(i), pkg, UserHandle.getUserId(uid)); } clipboard.activePermissionOwners.add(pkg); } }
private final void grantItemLocked(ClipData.Item item, String pkg, int userId) { if (item.getUri() != null) { grantUriLocked(item.getUri(), pkg, userId); } Intent intent = item.getIntent(); if (intent != null && intent.getData() != null) { grantUriLocked(intent.getData(), pkg, userId); } }
private final void grantUriLocked(Uri uri, String pkg, int userId) { /* 调用ActivityManagerService的grantUriPermissionFromOwner函数, 注意第二个参数传递的是CBS所在的进程的uid,该函数内部也检查权限 调用成功后,pasete就被授予了对应的uri的读权限 */ long ident = Binder.clearCallingIdentity(); try { int sourceUserId = ContentProvider.getUserIdFromUri(uri, userId); uri = ContentProvider.getUriWithoutUserId(uri); mAm.grantUriPermissionFromOwner(mPermissionOwner, Process.myUid(), pkg, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION, sourceUserId, userId); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(ident); } }
0 0
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- Java 8: Stream Reduction Operations
- C语言在执行完程序后如何使控制台保留在桌面上
- Spring-amqp 1.6.1 生产者与消费者消息确认配置与使用
- 调用拨打电话界面、直接拨打电话、调用发送短信的界面、调用系统浏览器
- 语音信号处理之(三)矢量量化(Vector Quantization)
- 欢迎使用CSDN-markdown编辑器
- Codeforces Round #375 (Div. 2) C (贪心)
- AngularJS系列之JavaScript继承
- crontab -e
- Codeforces 406A Unusual Product【暴力找规律】
- 多线程复习-NSOperation
- 红透半边天的VR(虚拟现实)产业
- 【笔记】ngrok安装方法
- Uva1593 Alignment of Code 【vector,stream应用】【习题5-1】