[Android官方API阅读]___

看官方文档在抓基础,继续吸收官方的观点跟重点,希望自己能坚持下去
以下的官方文档阅读,会贴出原文,会有一下几个点:
1.读到觉得是重点或者又一次深入理解到的地方会用红色标注
2.觉得需要用中文表达一下的地方下面会跟翻译,其中翻译中也会加入自己的看法(翻译的不好请见谅,欢迎指正,谢谢)


                                   System Permissions

Androidis a privilege-separated operatingsystem, in which each application runs with a distinct system identity (Linuxuser ID and group ID). Parts of the system are also separated into distinctidentities. Linux thereby isolates applications from each other andfrom the system.

Android是一个特权分隔的操作系统,每个app都会带着系统唯一标识(LinuxUIDGID)来运行系统的某些部分也被分隔成唯一的标识从而Linux系统可以把每个app与其他app隔离开来.

Additionalfiner-grained security features are provided through a "permission"mechanism that enforces restrictions on the specific operations that aparticular process can perform, and per-URI permissions for granting adhoc access to specific pieces of data.

额外的会提供一个指纹验证的安全功能的权限机制,可以强制的限制在特殊的进程中进行特殊的操作,并且使用URI前缀权限机制可以对点对点进行授权访问一些特定的数据.

Thisdocument describes how application developers can use the security featuresprovided by Android. A more general Android SecurityOverview is provided in the Android Open Source Project.

Security Architecture


Acentral design point of the Android security architecture is that noapplication, by default, has permission to perform any operations that wouldadversely impact other applications, the operating system, or the user. Thisincludes reading or writing the user's private data (such as contacts oremails), reading or writing another application's files, performing networkaccess, keeping the device awake, and so on.

Android安全架构设计的一个中心点是:默认情况下,任何app都不能拥有对其他app、操作系统,或者用户做任何操作的权限包括读或写用户的私有数据(例如联系人或者邮件),读写其他app的文件,访问网络,保持设备唤醒等.

Becauseeach Android application operates in a process sandbox, applications mustexplicitly share resources and data. They do this by declaring the permissions theyneed for additional capabilities not provided by the basic sandbox.Applications statically declare the permissions they require, and the Androidsystem prompts the user for consent atthe time the application is installed. Android has no mechanism for grantingpermissions dynamically (at run-time) because it complicates the userexperience to the detriment of security.

因为每个Android app的操作都在进程沙盒里进行,app必须显式的去共享资源和数据通过声明在它们需要的并且在基本沙盒里没有提供的额外的权限. app需要静态的声明它们需要的权限,并且Android系统会在app安装时给用户提示来取得用户的同意.Android并不拥有在运行时动态授权的机制,因为一些不利的安全问题会让用户体验变得复杂

Theapplication sandbox does not depend on the technology used to build an application.In particular the Dalvik VM is not a security boundary, and any app can runnative code (see the Android NDK).All types of applications — Java, native, and hybrid — are sandboxed in thesame way and have the same degree of security from each other.

app沙盒并不依赖于构建一个app的技术在指定的DVM中并没有安全边界,任何app都可以运行本地代码所有类型的app如:纯Java的、纯native的,或者混合的,互相都会以同样的方式、统一的安全制度存在于沙盒中.

Application Signing


AllAPKs (.apk files)must be signed with a certificate whose private key is held by their developer.This certificate identifies the author of the application. The certificatedoes not need to be signed by a certificate authority; it isperfectly allowable, and typical, for Android applications to use self-signedcertificates. The purpose of certificates in Android is to distinguishapplication authors. This allows the system to grant or deny applicationsaccess to signature-levelpermissions and to grant or deny an application's request to begiven the same Linux identity as another application.

所有的apk文件都必须要用开发者的私有证书来签名这个证书都唯一标识着此app的开发者证书不需要再用开发者的证书进行再度签名;它已经被完全的许可了,Androidapp使用证书自己签名的证书而此证书的目的就是来区别app的开发者这样允许系统授权或拒绝某一app可以访问签名级别的权限,还可以授权或拒绝app请求被赋予linux唯一标识的权限

User IDs and File Access


At install time, Android gives each package a distinctLinux user ID. The identity remains constant for theduration of the package's life on that device. On a different device, the samepackage may have a different UID; what matters is that each package has adistinct UID on a given device.

在安装时,Android会给予每一个软件包一个唯一的Linux UID这个设备上的软件包的标识会在其生命周期中保持不变而在另一个不同的设备,同一个软件包会有不同的UID;重要的是每个软件包在某一个设备上只会有一个唯一的UID.

Becausesecurity enforcement happens at the processlevel, the code of any two packages cannot normally run in thesame process, since they need to run as different Linux users. You can usethe sharedUserId attributein the AndroidManifest.xml's manifest tagof each package to have them assigned the same user ID. By doing this, forpurposes of security the two packages are then treated as being the sameapplication, with the same user ID and file permissions. Note that in order toretain security, only two applications signed with the same signature (andrequesting the same sharedUserId) will be given the same user ID.

因为安全的强制实施是在进程级别上的,任何两个软件包的代码不能运行在同一进程上,因为它们需要以不同的Linux用户身份来运行(不同的UID). 你可以通过在每个软件包里的AndroidManifest.xml 文件中设置sharedUserId 标签的属性值来请求系统赋予相同的UID. 如果这样做,安全机制会把这样两个app会被当做是同一个app,拥有相同的UID和文件权限请注意为了保持(记住)它们的安全权限,这两个app必须是使用相同的签名才能这么做

Anydata stored by an application will be assigned that application's user ID, andnot normally accessible to other packages. When creating a new file with getSharedPreferences(String,int)openFileOutput(String,int), or openOrCreateDatabase(String,int, SQLiteDatabase.CursorFactory),you can use theMODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE flagsto allow any other package to read/write the file. When setting these flags,the file is still owned by your application, but its global read and/or writepermissions have been set appropriately so any other application can see it.

任何被app保存的数据都被赋予该appUID,不能够正常地访问其他的软件包当使用以下方法创建了一个新文件时:getSharedPreferences(String,int)openFileOutput(String,int), or openOrCreateDatabase(String,int, SQLiteDatabase.CursorFactory)你可以使用MODE_WORLD_READABLE 或者和 MODE_WORLD_WRITEABLE标志来允许其他软件包读或写这个文件当设置了这些标志时,文件仍然是属于你的app,但被适当的设置了全局读或写的权限就可以让其他app看见了.

Using Permissions


Abasic Android application has no permissions associated with it by default,meaning it cannot do anything that would adversely impact the user experienceor any data on the device. To make use of protected features of the device, youmust include in your AndroidManifest.xml one or more  tagsdeclaring the permissions that your application needs.

一个基本你的Androidapp默认情况下是不跟任何权限关联的,这样就意味着它不能做任何事情而严重的影响了用户体验和不能读或写设备上的任何数据了为了利用设备的保护功能,你必须要在 AndroidManifest.xml 文件中包含一个到多个的 标签来声明你app中需要的权限.

Forexample, an application that needs to monitor incoming SMS messages wouldspecify:

 xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.app.myapp" >
     android:name="android.permission.RECEIVE_SMS" />
    ...

Atapplication install time, permissions requested by the application are grantedto it by the package installer, based on checks against the signatures of theapplications declaring those permissions and/or interaction with theuser. No checks with the user are done while an application isrunning; the app is either granted a particular permission when installed, andcan use that feature as desired, or the permission is not granted and anyattempt to use the feature fails without prompting the user.

app安装期间,app请求的权限会被软件包安装器来授予,它可以检查app的签名以及授予app所声明的想要和用户交互的一些权限app运行期间则不会检查;app会在安装完成的时候被授予一些指定的权限,就能够按照期望的使用那些功能了,如果权限没有被授予而app试图获得那些功能就会失败.

Oftentimes a permission failure will result in a SecurityException beingthrown back to the application. However, this is not guaranteedto occur everywhere. For example, the sendBroadcast(Intent) methodchecks permissions as data is being delivered to each receiver, after themethod call has returned, so you will not receive an exception if there arepermission failures. In almost all cases, however, a permission failure will beprinted to the system log.

通常几次的权限申请失败会导致SecurityException 异常被抛回app. 但是,会确保不会在任何地方发生,sendBroadcast(Intent)方法在数据被提交到每一个receiver时会检查其权限,当方法返回时,如果权限失败你将不会接到一个异常几乎全部的情况都是这样,但是这样的权限失败信息会被打印到系统log

However,in a normal user situation (such as when the app is installed from Google PlayStore), an app cannot be installed if the user does not grant the app each ofthe requested permissions. So you generally don't need to worry about runtimefailures caused by missing permissions because the mere fact that the app isinstalled at all means that your app has been granted its desired permissions.

然而,在用户正常使用的情况下,一个app是不会在被用户给每一个权限授权的情况下被安装到你的设备之中的所以你可以不必担心因为失去某些权限而在运行时的产生的错误,因为实际上当你的app被安装在设备上的时候就意味着你的app已经被授予了它期望的权限了.

Thepermissions provided by the Android system can be found at Manifest.permissionAnyapplication may also define and enforce its own permissions, so this is not acomprehensive list of all possible permissions.

一些其他的app可能会定义一些自己的权限,所以这不是一个很完全的权限列表

Aparticular permission may be enforced at a number of places during yourprogram's operation:

一些特殊的权限可能在你程序操作期间会在一下几个地方被授予.

·                        Atthe time of a call into the system, to prevent an application from executingcertain functions.

在系统调用之时,来防止一个app执行某些确定的函数.

·                        Whenstarting an activity, to prevent applications from launching activities ofother applications.

在启动一个activity之时,来防止app启动到其他appacitivity

·                        Bothsending and receiving broadcasts, to control who can receive your broadcast orwho can send a broadcast to you.

在发送和接受广播之时,来控制广播的接收或者发送者

·                        Whenaccessing and operating on a content provider.

当访问或操作一个 content provider 

·                        Bindingto or starting a service.

绑定一个服务时

Caution: Overtime, new restrictions may be added to the platform such that, in order to usecertain APIs, your app must request a permission that it previously did notneed. Because existing apps assume access to those APIs is freely available,Android may apply the new permission request to the app's manifest to avoidbreaking the app on the new platform version. Android makes the decision as towhether an app might need the permission based on the value provided forthe targetSdkVersion attribute. If the valueis lower than the version in which the permission was added, then Android addsthe permission.

注意:未来的时间里,新的限制条件可能会被加入到平台之中,例如,为了能够使用将来的API,你的app必须要申请一些之前版本不需要的权限因为现在存在的app被假定可以大胆的访问那些APIAndroid在未来可能会引用到一些新的权限到appmenifest文件中,来避免打断一些app在新版本的平台上运行.Android可以根据targetSdkVersion 的属性值来决定一个app是否需要这些权限如果此属性值比平台版本低且加入了某些权限,那么Android会为了添加那些权限的.

Forexample, the WRITE_EXTERNAL_STORAGE permissionwas added in API level 4 to restrict access to the shared storage space. Ifyour targetSdkVersion is 3 or lower, thispermission is added to your app on newer versions of Android.

Bewarethat if this happens to your app, your app listing on Google Play will showthese required permissions even though your app might not actually requirethem.

例如WRITE_EXTERNAL_STORAGE 权限是在API等级为4的时候加入的,用来限制访问共享存储空间的权限如果你的targetSdkVersion 属性值为3或者更低,而这个权限是在一个较新的版本中被添加的请注意这样的情况,你的app会在Google Play上列出一些请求的权限和一些甚至是你不需要的权限.

Toavoid this and remove the default permissions you don't need, always updateyour targetSdkVersion to be as high aspossible. You can see which permissions were added with each release inthe Build.VERSION_CODESdocumentation.

为了避免这个问题,一处你不需要的默认权限,总是将你的targetSdkVersion 尽可能的更新到最高并且你可以在一些release版本的文档中看到被新添加的权限.

Declaring and Enforcing Permissions


Toenforce your own permissions(自定义权限), you must first declare them in your AndroidManifest.xml usingone or more tags.

Forexample, an application that wants to controlwho can start one of its activities coulddeclare a permission for this operation as follows:

 xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.me.app.myapp" >
     android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"
        android:label="@string/permlab_deadlyActivity"
        android:description="@string/permdesc_deadlyActivity"
        android:permissionGroup="android.permission-group.COST_MONEY"
        android:protectionLevel="dangerous" />
    ...

The  attributeis required, telling the system how the user is to be informed of applicationsrequiring the permission, or who is allowed to hold that permission, asdescribed in the linked documentation.

  属性是必要的,来告知系统用户应该怎样接到app请求权限的通知,或者谁将会持有那个权限

The  attributeis optional, and only used to help the system display permissions to the user.You will usually want to set this to either a standard system group (listed inandroid.Manifest.permission_group)or in more rare cases to one defined by yourself. Itis preferred to use an existing group, as this simplifies the permission UIshown to the user.

 属性是可选的,仅用来帮助系统来向用户展示权限通常情况你可以将这个值设置为标准的系统组或者更稀有的情况下可以使用自定义组如果只是简单的向用户展示一些UI,推荐使用已经存在的群组.

Notethat both a label and description should be supplied for the permission. Theseare string resources that can be displayed to the user when they are viewing a listof permissions (android:label)or details on a single permission ( android:description).The label should be short, a few words describing the key piece offunctionality the permission is protecting. The description should be a couplesentences describing what the permission allows a holder to do. Our conventionfor the description is two sentences, the first describing the permission, thesecond warning the user of what bad things can happen if an application isgranted the permission.

注意labeldescription两个属性标签在权限声明当中应该要提供的有一些string资源可以当用户在视察权限列表时来向用户展示,或者展示单个权限的详细形式时.Label属性应该要短一些,只需要该权限功能的几个关键词来描述即可.description 属性应该用成对的语句出现来描述该权限允许持有者做的工作我们的会约定description 属性会用两句话描述出来:第一句描述权限,第二句来警告用户如果授予了该权限会发生什么坏的事情.

Hereis an example of a label and description for the CALL_PHONE permission:

     name="permlab_callPhone">directly call phone numbers
     name="permdesc_callPhone">Allows the application to call
        phone numbers without your intervention(介入). Malicious(恶意的) applications may
        cause unexpected calls on your phone bill. Notethat this does not
        allow the application to call emergency numbers.

Youcan look at the permissions currently defined in the system with the Settingsapp and the shell command adb shell pm list permissions. To use the Settings app, go to Settings> Applications. Pick an app and scroll down to see the permissions that theapp uses. For developers, the adb '-s' optiondisplays the permissions in a form similar to how the user will see them:

$ adb shell pm list permissions -s
All Permissions:

Network communication: view Wi-Fi state, create Bluetooth connections, full
Internet access, view network state

Your location: access extra location provider commands, fine (GPS) location,
mock location sources for testing, coarse (network-based) location

Services that cost you money: send SMS messages, directly call phone numbers

...

Enforcing Permissions in AndroidManifest.xml

High-levelpermissions restricting access to entire components of the system orapplication can be applied through your AndroidManifest.xml.All that this requires is including an android:permission attributeon the desired component, naming the permission that will be used to controlaccess to it.

高级的权限会限制app或者系统的整个组件的访问,这可以在AndroidManifest.xml件中提供只需在需要的组件上包含android:permission 属性,然后声明要使用访问控制权限的名称即可.

Activity permissions(applied to the  tag)restrict who can start the associated activity. The permission is checkedduring Context.startActivity() and Activity.startActivityForResult();if the caller does not have the required permission then SecurityException isthrown from the call.

使用 标签来定义activity权限可以限制谁能启动它. 权限检查阶段是在调用 Context.startActivity() and Activity.startActivityForResult() 函数时来检查的;如果调用者没有所需要的权限则会抛出SecurityException 异常

Service permissions(applied to the  tag)restrict who can start or bind to the associated service. The permission ischecked during Context.startService()Context.stopService() and Context.bindService();if the caller does not have the required permission then SecurityException isthrown from the call.

使用标签来定义Service权限可以限制谁能启动或者绑定它. 权限检查阶段是在调用 Context.startService()Context.stopService() and Context.bindService() 函数时来检查的;如果调用者没有所需要的权限则会抛出SecurityException 异常

 

BroadcastReceiver permissions(applied to the  tag)restrict who can send broadcasts to the associated receiver. The permission ischecked after Context.sendBroadcast() returns,as the system tries to deliver the submitted broadcast to the given receiver.As a result, a permission failure will not result in an exception being thrownback to the caller; it will just not deliver the intent. In the same way, apermission can be supplied to Context.registerReceiver() tocontrol who can broadcast to a programmatically registered receiver. Going theother way, a permission can be supplied when calling Context.sendBroadcast() torestrict which BroadcastReceiver objects are allowed to receive the broadcast(see below).

使用标签来定义BroadcastReceiver 权限可以限谁能发送广播到接收者. 权限检查阶段是在调用  Context.sendBroadcast() 函数返回时;如果系统尝试发出一个广播到指定的接收者结果是系统不会再权限申请失败的情况下导致抛回异常到调用者;而是只是提交到intent. 在一些相同的情况下, 一些权限可以通过 Context.registerReceiver() 方法的调用来控制谁能接受此广播而另一种情况是:通过调用Context.sendBroadcast() 方法来限制允许哪些BroadcastReceiver对象可以接受一个广播.

ContentProvider permissions(applied to the  tag)restrict who can access the data in aContentProvider.(Content providers have an important additional security facility available tothem called URI permissions whichis described later.) Unlike the other components, there are two separatepermission attributes you can set: android:readPermission restrictswho can read from the provider, andandroid:writePermission restrictswho can write to it. Note that if a provider is protected with both a read andwrite permission, holding only the write permission does not mean you can readfrom a provider. The permissions are checked when you first retrieve a provider(if you don't have either permission, a SecurityException will be thrown), andas you perform operations on the provider. UsingContentResolver.query() requiresholding the read permission; using ContentResolver.insert(),ContentResolver.update()ContentResolver.delete() requiresthe write permission. In all of these cases, not holding the requiredpermission results in a SecurityException beingthrown from the call.

使用标签可以限制谁能访问ContentProvider的数据. (Content providers拥有一个很重要的附加权限限制机制,就是URI权限机制). 与其他组件不同的是,他分别拥有两个权限来限制读和写注意如果一个provider同时被读和写权限来限制就会被保护起来权限将在第一次获得 provider 的时候来检查(如果你也没有权限,那么SecurityException异常会抛出),使用ContentResolver.query()来申请持有读权限,使用 ContentResolver.insert(),ContentResolver.update()ContentResolver.delete()来申请持有写权限在这所有的情况中如果没有权限的话会导致SecurityException异常会跑回到调用者

Enforcing Permissions when SendingBroadcasts

Inaddition to the permission enforcing who can send Intents to a registered BroadcastReceiver (asdescribed above), you can also specify a required permission when sending abroadcast. By calling Context.sendBroadcast() witha permission string, you require that a receiver's application must hold thatpermission in order to receive your broadcast.

Notethat both a receiver and a broadcaster can require a permission. When thishappens, both permission checks must pass for the Intent to be delivered to theassociated target.

一些附加的权限可以限制谁能发送intent到已注册的BroadcastReceiver, 你也可以指定一个需要发送广播的权限若你使用有权限的调用Context.sendBroadcast()方法,你需要接收者app必须得持有那个权限来接收广播

注意接收者和广播发送者都需要权限,双方的权限都必须检查通过才能提交intent到已关联的目标对象.

Other Permission Enforcement

Arbitrarilyfine-grained permissions can be enforced at any call into a service. This isaccomplished with the Context.checkCallingPermission() method.Call with a desired permission string and it will return an integer indicatingwhether that permission has been granted to the current calling process. Notethat this can only be used when you are executing a call coming in from anotherprocess, usually through an IDL interface published from a service or in someother way given to another process.

在任何调用到service时,任意一些有意的权限都可以被实施通过调用Context.checkCallingPermission()方法来完成被一个有期望权限的字符串调用,可以返回一个整型来致命是否权限被当前的进程被授予了注意当你从另一个进程执行的时候会被调用到,通常通过一个serviceIDL借口来发布或者通过其他方式授予与其他的进程

Thereare a number of other useful ways to check permissions. If you have the pid ofanother process, you can use the Context method Context.checkPermission(String,int, int) to check a permission against thatpid. If you have the package name of another application, you can use thedirect PackageManager method PackageManager.checkPermission(String,String) to find out whether that particularpackage has been granted a specific permission.

这里有几种有用的方式来检查权限如果你有其他进程的pid,你可以使用ContextContext.checkPermission(String,int, int)方法来检查这个权限是否匹配如果你有别的软件包的名字,你也可以用PackageManagerPackageManager.checkPermission(String,String)方法来查找指定的软件包是否被赋予了权限

URIPermissions


Thestandard permission system described so far is often not sufficient when usedwith content providers. A content provider may want to protect itself with readand write permissions, while its direct clients also need to hand specific URIsto other applications for them to operate on. A typical example is attachmentsin a mail application. Access to the mail should be protected by permissions,since this is sensitive user data. However, if a URI to an image attachment isgiven to an image viewer, that image viewer will not have permission to openthe attachment since it has no reason to hold a permission to access alle-mail.

标准的系统权限对于使用contentproviders是远远不够的一个content providers可能想要保护自己的读写权限,当它的客户端也需要指定一些URIs来让其他程序来操作一个典型的例子是邮件app 里的附件访问到邮件里是有一些权限来保护的, 因为这是用户的敏感数据但是, 如果一个图片附件的URI被给了image viewer,那image viewer将会得不到权限来打来图片附件,因为他并未持有访问邮件的权限.

Thesolution to this problem is per-URI permissions: when starting an activity orreturning a result to an activity, the caller can set Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION.This grants the receiving activity permission access the specific data URI inthe Intent, regardless of whether it has any permission to access data in thecontent provider corresponding to the Intent.

为了解决这个每个URI权限的问题: 当启动一个activity时来返回一个结果给一个activity 调用者可以设置Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION.权限.这样就授予了接收activity的权限来访问指定uri携带的数据而无视是否有任何权限来访问 content provider相应的权限了.

Thismechanism allows a common capability-style model where user interaction(opening an attachment, selecting a contact from a list, etc) drives ad-hocgranting of fine-grained permission.This can be a key facility for reducingthe permissions needed by applications toonly those directly related totheir behavior.

这种机制允许在与用户交互的地方使用一个通用的风格属性模型 (打开一个附件,从联系人列表中选择一个联系人等)来驱动点对点的细粒度授权.这就可以成为减少那些只与app行为有直接相关的一些权限的关键.

Thegranting of fine-grained URI permissions does, however, require somecooperation with the content provider holding those URIs. It is stronglyrecommended that content providers implement this facility, and declare thatthey support it through the android:grantUriPermissions attributeor  tag.

细粒度的URI授权模式,需要与持有在那些URIscontent provider合作,强烈建议那些contentproviders实现这个方案,并且使用android:grantUriPermissions 属性或者标签来声明.

你可能感兴趣的:(Android官方API阅读,Android)