在这篇文章中,我们将为您详细介绍golang语言中的context详解,GoConcurrencyPatterns:Context的内容,并且讨论关于golangcontext.done的相关问题。此
在这篇文章中,我们将为您详细介绍golang语言中的context详解,Go Concurrency Patterns: Context的内容,并且讨论关于golang context.done的相关问题。此外,我们还会涉及一些关于.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么、Android中Context详解 ---- 你所不知道的Context、Android中Context详解---- 你所不知道的Context、android中,下面代码中 public PlainView(Context context){,Context context是什么意思呢的知识,以帮助您更全面地了解这个主题。
本文目录一览:- golang语言中的context详解,Go Concurrency Patterns: Context(golang context.done)
- .NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么
- Android中Context详解 ---- 你所不知道的Context
- Android中Context详解---- 你所不知道的Context
- android中,下面代码中 public PlainView(Context context){,Context context是什么意思呢
golang语言中的context详解,Go Concurrency Patterns: Context(golang context.done)
https://blog.golang.org/context
Introduction
In Go servers, each incoming request is handled in its own goroutine. Request handlers often start additional goroutines to access backends such as databases and RPC services. The set of goroutines working on a request typically needs access to request-specific values such as the identity of the end user, authorization tokens, and the request''s deadline. When a request is canceled or times out, all the goroutines working on that request should exit quickly so the system can reclaim any resources they are using.
At Google, we developed a context
package that makes it easy to pass request-scoped values, cancelation signals, and deadlines across API boundaries to all the goroutines involved in handling a request. The package is publicly available as context. This article describes how to use the package and provides a complete working example.
Context
The core of the context
package is the Context
type:
// A Context carries a deadline, cancelation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
(This description is condensed; the godoc is authoritative.)
The Done
method returns a channel that acts as a cancelation signal to functions running on behalf of the Context
: when the channel is closed, the functions should abandon their work and return. The Err
method returns an error indicating why the Context
was canceled. The Pipelines and Cancelation article discusses the Done
channel idiom in more detail.
A Context
does not have a Cancel
method for the same reason the Done
channel is receive-only: the function receiving a cancelation signal is usually not the one that sends the signal. In particular, when a parent operation starts goroutines for sub-operations, those sub-operations should not be able to cancel the parent. Instead, the WithCancel
function (described below) provides a way to cancel a new Context
value.
A Context
is safe for simultaneous use by multiple goroutines. Code can pass a single Context
to any number of goroutines and cancel that Context
to signal all of them.
The Deadline
method allows functions to determine whether they should start work at all; if too little time is left, it may not be worthwhile. Code may also use a deadline to set timeouts for I/O operations.
Value
allows a Context
to carry request-scoped data. That data must be safe for simultaneous use by multiple goroutines.
Derived contexts
The context
package provides functions to derive new Context
values from existing ones. These values form a tree: when a Context
is canceled, all Contexts
derived from it are also canceled.
Background
is the root of any Context
tree; it is never canceled:
// Background returns an empty Context. It is never canceled, has no deadline,
// and has no values. Background is typically used in main, init, and tests,
// and as the top-level Context for incoming requests.
func Background() Context
WithCancel
and WithTimeout
return derived Context
values that can be canceled sooner than the parent Context
. The Context
associated with an incoming request is typically canceled when the request handler returns. WithCancel
is also useful for canceling redundant requests when using multiple replicas. WithTimeout
is useful for setting a deadline on requests to backend servers:
// WithCancel returns a copy of parent whose Done channel is closed as soon as
// parent.Done is closed or cancel is called.
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
// A CancelFunc cancels a Context.
type CancelFunc func()
// WithTimeout returns a copy of parent whose Done channel is closed as soon as
// parent.Done is closed, cancel is called, or timeout elapses. The new
// Context''s Deadline is the sooner of now+timeout and the parent''s deadline, if
// any. If the timer is still running, the cancel function releases its
// resources.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithValue
provides a way to associate request-scoped values with a Context
:
// WithValue returns a copy of parent whose Value method returns val for key.
func WithValue(parent Context, key interface{}, val interface{}) Context
The best way to see how to use the context
package is through a worked example.
Example: Google Web Search
Our example is an HTTP server that handles URLs like /search?q=golang&timeout=1s
by forwarding the query "golang" to the Google Web Search API and rendering the results. The timeout
parameter tells the server to cancel the request after that duration elapses.
The code is split across three packages:
- server provides the
main
function and the handler for/search
. - userip provides functions for extracting a user IP address from a request and associating it with a
Context
. - google provides the
Search
function for sending a query to Google.
The server program
The server program handles requests like /search?q=golang
by serving the first few Google search results for golang
. It registers handleSearch
to handle the /search
endpoint. The handler creates an initial Context
called ctx
and arranges for it to be canceled when the handler returns. If the request includes the timeout
URL parameter, the Context
is canceled automatically when the timeout elapses:
func handleSearch(w http.ResponseWriter, req *http.Request) {
// ctx is the Context for this handler. Calling cancel closes the
// ctx.Done channel, which is the cancellation signal for requests
// started by this handler.
var (
ctx context.Context
cancel context.CancelFunc
)
timeout, err := time.ParseDuration(req.FormValue("timeout"))
if err == nil {
// The request has a timeout, so create a context that is
// canceled automatically when the timeout expires.
ctx, cancel = context.WithTimeout(context.Background(), timeout)
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel() // Cancel ctx as soon as handleSearch returns.
}
The handler extracts the query from the request and extracts the client''s IP address by calling on the
userip
package. The client''s IP address is needed for backend requests, so
handleSearch
attaches it to
ctx
:
// Check the search query.
query := req.FormValue("q")
if query == "" {
http.Error(w, "no query", http.StatusBadRequest)
return
}
// Store the user IP in ctx for use by code in other packages.
userIP, err := userip.FromRequest(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx = userip.NewContext(ctx, userIP)
The handler calls google.Search
with ctx
and the query
:
// Run the Google search and print the results.
start := time.Now()
results, err := google.Search(ctx, query)
elapsed := time.Since(start)
If the search succeeds, the handler renders the results:
if err := resultsTemplate.Execute(w, struct {
Results google.Results
Timeout, Elapsed time.Duration
}{
Results: results,
Timeout: timeout,
Elapsed: elapsed,
}); err != nil {
log.Print(err)
return
}
Package userip
The userip package provides functions for extracting a user IP address from a request and associating it with a Context
. A Context
provides a key-value mapping, where the keys and values are both of type interface{}
. Key types must support equality, and values must be safe for simultaneous use by multiple goroutines. Packages like userip
hide the details of this mapping and provide strongly-typed access to a specific Context
value.
To avoid key collisions, userip
defines an unexported type key
and uses a value of this type as the context key:
// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type key int
// userIPkey is the context key for the user IP address. Its value of zero is
// arbitrary. If this package defined other context keys, they would have
// different integer values.
const userIPKey key = 0
FromRequest
extracts a userIP
value from an http.Request
:
func FromRequest(req *http.Request) (net.IP, error) {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
}
}
NewContext
returns a new Context
that carries a provided userIP
value:
func NewContext(ctx context.Context, userIP net.IP) context.Context {
return context.WithValue(ctx, userIPKey, userIP)
}
FromContext
extracts a userIP
from a Context
:
func FromContext(ctx context.Context) (net.IP, bool) {
// ctx.Value returns nil if ctx has no value for the key;
// the net.IP type assertion returns ok=false for nil.
userIP, ok := ctx.Value(userIPKey).(net.IP)
return userIP, ok
}
Package google
The google.Search function makes an HTTP request to the Google Web Search API and parses the JSON-encoded result. It accepts a Context
parameter ctx
and returns immediately if ctx.Done
is closed while the request is in flight.
The Google Web Search API request includes the search query and the user IP as query parameters:
func Search(ctx context.Context, query string) (Results, error) {
// Prepare the Google Search API request.
req, err := http.NewRequest("GET", "https://ajax.googleapis.com/ajax/services/search/web?v=1.0", nil)
if err != nil {
return nil, err
}
q := req.URL.Query()
q.Set("q", query)
// If ctx is carrying the user IP address, forward it to the server.
// Google APIs use the user IP to distinguish server-initiated requests
// from end-user requests.
if userIP, ok := userip.FromContext(ctx); ok {
q.Set("userip", userIP.String())
}
req.URL.RawQuery = q.Encode()
}
Search
uses a helper function, httpDo
, to issue the HTTP request and cancel it if ctx.Done
is closed while the request or response is being processed. Search
passes a closure to httpDo
handle the HTTP response:
var results Results
err = httpDo(ctx, req, func(resp *http.Response, err error) error {
if err != nil {
return err
}
defer resp.Body.Close()
// Parse the JSON search result.
// https://developers.google.com/web-search/docs/#fonje
var data struct {
ResponseData struct {
Results []struct {
TitleNoFormatting string
URL string
}
}
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return err
}
for _, res := range data.ResponseData.Results {
results = append(results, Result{Title: res.TitleNoFormatting, URL: res.URL})
}
return nil
})
// httpDo waits for the closure we provided to return, so it''s safe to
// read results here.
return results, err
The httpDo
function runs the HTTP request and processes its response in a new goroutine. It cancels the request if ctx.Done
is closed before the goroutine exits:
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
tr := &http.Transport{}
client := &http.Client{Transport: tr}
c := make(chan error, 1)
go func() { c <- f(client.Do(req)) }()
select {
case <-ctx.Done():
tr.CancelRequest(req)
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}
Adapting code for Contexts
Many server frameworks provide packages and types for carrying request-scoped values. We can define new implementations of the Context
interface to bridge between code using existing frameworks and code that expects a Context
parameter.
For example, Gorilla''s github.com/gorilla/context package allows handlers to associate data with incoming requests by providing a mapping from HTTP requests to key-value pairs. In gorilla.go, we provide a Context
implementation whose Value
method returns the values associated with a specific HTTP request in the Gorilla package.
Other packages have provided cancelation support similar to Context
. For example, Tomb provides a Kill
method that signals cancelation by closing a Dying
channel. Tomb
also provides methods to wait for those goroutines to exit, similar to sync.WaitGroup
. In tomb.go, we provide a Context
implementation that is canceled when either its parent Context
is canceled or a provided Tomb
is killed.
Conclusion
At Google, we require that Go programmers pass a Context
parameter as the first argument to every function on the call path between incoming and outgoing requests. This allows Go code developed by many different teams to interoperate well. It provides simple control over timeouts and cancelation and ensures that critical values like security credentials transit Go programs properly.
Server frameworks that want to build on Context
should provide implementations of Context
to bridge between their packages and those that expect a Context
parameter. Their client libraries would then accept a Context
from the calling code. By establishing a common interface for request-scoped data and cancelation, Context
makes it easier for package developers to share code for creating scalable services.
By Sameer Ajmani
Using contexts to avoid leaking goroutines
https://rakyll.org/leakingctx/
The context package makes it possible to manage a chain of calls within the same call path by signaling context’s Done channel.
In this article, we will examine how to use the context package to avoid leaking goroutines.
Assume, you have a function that starts a goroutine internally. Once this function is called, the caller may not be able to terminate the goroutine started by the function.
// gen is a broken generator that will leak a goroutine.
func gen() <-chan int {
ch := make(chan int)
go func() {
var n int
for {
ch <- n
n++
}
}()
return ch
}
The generator above starts a goroutine with an infinite loop, but the caller consumes the values until n is equal to 5.
// The call site of gen doesn''t have a
for n := range gen() {
fmt.Println(n)
if n == 5 {
break
}
}
Once the caller is done with the generator (when it breaks the loop), the goroutine will run forever executing the infinite loop. Our code will leak a goroutine.
We can avoid the problem by signaling the internal goroutine with a stop channel but there is a better solution: cancellable contexts. The generator can select on a context’s Done channel and once the context is done, the internal goroutine can be cancelled.
// gen is a generator that can be cancellable by cancelling the ctx.
func gen(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
var n int
for {
select {
case <-ctx.Done():
return // avoid leaking of this goroutine when ctx is done.
case ch <- n:
n++
}
}
}()
return ch
}
Now, the caller can signal the generator when it is done consuming. Once cancel function is called, the internal goroutine will be returned.
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // make sure all paths cancel the context to avoid context leak
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
cancel()
break
}
}
// ...
The full program is available as a gist.
Context and Cancellation of goroutines
http://dahernan.github.io/2015/02/04/context-and-cancellation-of-goroutines/
Yesterday I went to the event London Go Gathering, where all the talks had a great level, but particulary Peter Bourgon gave me idea to write about the excelent package context.
Context is used to pass request scoped variables, but in this case I’m only going to focus in cancelation signals.
Lets say that I have a program that execute a long running function, in this case work
and we run it in a separate go routine.
package main
import (
"fmt"
"sync"
"time"
)
var (
wg sync.WaitGroup
)
func work() error {
defer wg.Done()
for i := 0; i < 1000; i++ {
select {
case <-time.After(2 * time.Second):
fmt.Println("Doing some work ", i)
}
}
return nil
}
func main() {
fmt.Println("Hey, I''m going to do some work")
wg.Add(1)
go work()
wg.Wait()
fmt.Println("Finished. I''m going home")
}
$ go run work.go
Hey, I''m going to do some work
Doing some work 0
Doing some work 1
Doing some work 2
Doing some work 3
...
Doing some work 999
Finished. I''m going home
Now imagine that we have to call that work
function from a user interaction or a http request, we probably don’t want to wait forever for that goroutine to finish, so a common pattern is to set a timeout, using a buffered channel, like this:
package main
import (
"fmt"
"log"
"time"
)
func work() error {
for i := 0; i < 1000; i++ {
select {
case <-time.After(2 * time.Second):
fmt.Println("Doing some work ", i)
}
}
return nil
}
func main() {
fmt.Println("Hey, I''m going to do some work")
ch := make(chan error, 1)
go func() {
ch <- work()
}()
select {
case err := <-ch:
if err != nil {
log.Fatal("Something went wrong :(", err)
}
case <-time.After(4 * time.Second):
fmt.Println("Life is to short to wait that long")
}
fmt.Println("Finished. I''m going home")
}
$ go run work.go
Hey, I''m going to do some work
Doing some work 0
Doing some work 1
Life is to short to wait that long
Finished. I''m going home
Now, is a little bit better because, the main execution doesn’t have to wait for work
if it’s timing out.
But it has a problem, if my program is still running like for example a web server, even if I don’t wait for the function work
to finish, the goroutine it would be running and consuming resources. So I need a way to cancel that goroutine.
For cancelation of the goroutine we can use the context package. We have to change the function to accept an argument of type context.Context
, by convention it’s usuallly the first argument.
package main
import (
"fmt"
"sync"
"time"
"golang.org/x/net/context"
)
var (
wg sync.WaitGroup
)
func work(ctx context.Context) error {
defer wg.Done()
for i := 0; i < 1000; i++ {
select {
case <-time.After(2 * time.Second):
fmt.Println("Doing some work ", i)
// we received the signal of cancelation in this channel
case <-ctx.Done():
fmt.Println("Cancel the context ", i)
return ctx.Err()
}
}
return nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
fmt.Println("Hey, I''m going to do some work")
wg.Add(1)
go work(ctx)
wg.Wait()
fmt.Println("Finished. I''m going home")
}
$ go run work.go
Hey, I''m going to do some work
Doing some work 0
Cancel the context 1
Finished. I''m going home
This is pretty good!, apart that the code looks more simple to manage the timeout, now we are making sure that the function work
doesn’t waste any resource.
These examples are good to learn the basics, but let’s try to make it more real. Now the work
function is going to do an http request to a server and the server is going to be this other program:
package main
// Lazy and Very Random Server
import (
"fmt"
"math/rand"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", LazyServer)
http.ListenAndServe(":1111", nil)
}
// sometimes really fast server, sometimes really slow server
func LazyServer(w http.ResponseWriter, req *http.Request) {
headOrTails := rand.Intn(2)
if headOrTails == 0 {
time.Sleep(6 * time.Second)
fmt.Fprintf(w, "Go! slow %v", headOrTails)
fmt.Printf("Go! slow %v", headOrTails)
return
}
fmt.Fprintf(w, "Go! quick %v", headOrTails)
fmt.Printf("Go! quick %v", headOrTails)
return
}
Randomly is going to be very quick or very slow, we can check that with curl
$ curl http://localhost:1111/
Go! quick 1
$ curl http://localhost:1111/
Go! quick 1
$ curl http://localhost:1111/
*some seconds later*
Go! slow 0
So we are going to make an http request to this server, in a goroutine, but if the server is slow we are going to Cancel the request and return quickly, so we can manage the cancellation and free the connection.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"golang.org/x/net/context"
)
var (
wg sync.WaitGroup
)
// main is not changed
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
fmt.Println("Hey, I''m going to do some work")
wg.Add(1)
go work(ctx)
wg.Wait()
fmt.Println("Finished. I''m going home")
}
func work(ctx context.Context) error {
defer wg.Done()
tr := &http.Transport{}
client := &http.Client{Transport: tr}
// anonymous struct to pack and unpack data in the channel
c := make(chan struct {
r *http.Response
err error
}, 1)
req, _ := http.NewRequest("GET", "http://localhost:1111", nil)
go func() {
resp, err := client.Do(req)
fmt.Println("Doing http request is a hard job")
pack := struct {
r *http.Response
err error
}{resp, err}
c <- pack
}()
select {
case <-ctx.Done():
tr.CancelRequest(req)
<-c // Wait for client.Do
fmt.Println("Cancel the context")
return ctx.Err()
case ok := <-c:
err := ok.err
resp := ok.r
if err != nil {
fmt.Println("Error ", err)
return err
}
defer resp.Body.Close()
out, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Server Response: %s\n", out)
}
return nil
}
$ go run work.go
Hey, I''m going to do some work
Doing http request is a hard job
Server Response: Go! quick 1
Finished. I''m going home
$ go run work.go
Hey, I''m going to do some work
Doing http request is a hard job
Cancel the context
Finished. I''m going home
As you can see in the output, we avoid the slow responses from the server.
In the client the tcp connection is canceled so is not going to be busy waiting for a slow response, so we don’t waste resources.
Happy coding gophers!.
.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么
如何解决.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么?
.NET Core 中以下代码片段的替代方法是什么?
WebOperationContext webContext = WebOperationContext.Current;
webContext.OutgoingResponse.ContentType = "text/html";
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
Android中Context详解 ---- 你所不知道的Context
本文原创 ,转载必须注明出处 :http://blog.csdn.net/qinjuning
前言:本文是我读《Android内核剖析》第7章 后形成的读书笔记 ,在此向欲了解Android框架的书籍推荐此书。
大家好, 今天给大家介绍下我们在应用开发中最熟悉而陌生的朋友-----Context类 ,说它熟悉,是应为我们在开发中
时刻的在与它打交道,例如:Service、BroadcastReceiver、Activity等都会利用到Context的相关方法 ; 说它陌生,完全是
因为我们真正的不懂Context的原理、类结构关系。一个简单的问题是,一个应用程序App中存在多少个Context实例对象呢?
一个、两个? 在此先卖个关子吧。读了本文,相信您会豁然开朗的 。
Context,中文直译为“上下文”,SDK中对其说明如下:
Interface to global information about an application environment. This is an abstract class whose implementation
is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls
for application-level operations such as launching activities, broadcasting and receiving intents, etc
从上可知一下三点,即:
1、它描述的是一个应用程序环境的信息,即上下文。
2、该类是一个抽象(abstract class)类,Android提供了该抽象类的具体实现类(后面我们会讲到是ContextIml类)。
3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别操作,例如:启动一个Activity,发送广播,接受Intent
信息 等。。
于是,我们可以利用该Context对象去构建应用级别操作(application-level operations) 。
一、Context相关类的继承关系
相关类介绍:
Context类 路径: /frameworks/base/core/java/android/content/Context.java
说明: 抽象类,提供了一组通用的API。
源代码(部分)如下:
[java] view plaincopyprint?
public abstract class Context {
...
public abstract Object getSystemService(String name); //获得系统级服务
public abstract void startActivity(Intent intent); //通过一个Intent启动Activity
public abstract ComponentName startService(Intent service); //启动Service
//根据文件名得到SharedPreferences对象
public abstract SharedPreferences getSharedPreferences(String name,int mode);
...
}
ContextIml.java类 路径 :/frameworks/base/core/java/android/app/ContextImpl.java
说明:该Context类的实现类为ContextIml,该类实现了Context类的功能。请注意,该函数的大部分功能都是直接调用
其属性mPackageInfo去完成,这点我们后面会讲到。
源代码(部分)如下:
[java] view plaincopyprint?
/**
* Common implementation of Context API, which provides the base
* context object for Activity and other application components.
*/
class ContextImpl extends Context{
//所有Application程序公用一个mPackageInfo对象
/*package*/ ActivityThread.PackageInfo mPackageInfo;
@Override
public Object getSystemService(String name){
...
else if (ACTIVITY_SERVICE.equals(name)) {
return getActivityManager();
}
else if (INPUT_METHOD_SERVICE.equals(name)) {
return InputMethodManager.getInstance(this);
}
}
@Override
public void startActivity(Intent intent) {
...
//开始启动一个Activity
mMainThread.getInstrumentation().execStartActivity(
getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
}
}
ContextWrapper类 路径 :\frameworks\base\core\java\android\content\ContextWrapper.java
说明: 正如其名称一样,该类只是对Context类的一种包装,该类的构造函数包含了一个真正的Context引用,即ContextIml
对象。 源代码(部分)如下:
[java] view plaincopyprint?
public class ContextWrapper extends Context {
Context mBase; //该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
//创建Application、Service、Activity,会调用该方法给mBase属性赋值
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
@Override
public void startActivity(Intent intent) {
mBase.startActivity(intent); //调用mBase实例方法
}
}
ContextThemeWrapper类 路径:/frameworks/base/core/java/android/view/ContextThemeWrapper.java
说明:该类内部包含了主题(Theme)相关的接口,即android:theme属性指定的。只有Activity需要主题,Service不需要主题,
所以Service直接继承于ContextWrapper类。
源代码(部分)如下:
[java] view plaincopyprint?
public class ContextThemeWrapper extends ContextWrapper {
//该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
private Context mBase;
//mBase赋值方式同样有一下两种
public ContextThemeWrapper(Context base, int themeres) {
super(base);
mBase = base;
mThemeResource = themeres;
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
mBase = newBase;
}
}
Activity类 、Service类 、Application类本质上都是Context子类, 更多信息大家可以自行参考源代码进行理解。
二、 什么时候创建Context实例
熟悉了Context的继承关系后,我们接下来分析应用程序在什么情况需要创建Context对象的?应用程序创建Context实例的
情况有如下几种情况:
1、创建Application 对象时, 而且整个App共一个Application对象
2、创建Service对象时
3、创建Activity对象时
因此应用程序App共有的Context数目公式为:
总Context实例个数 = Service个数 + Activity个数 + 1(Application对应的Context实例)
具体创建Context的时机
1、创建Application对象的时机
每个应用程序在第一次启动时,都会首先创建Application对象。如果对应用程序启动一个Activity(startActivity)流程比较
清楚的话,创建Application的时机在创建handleBindApplication()方法中,该函数位于 ActivityThread.java类中 ,如下:
[java] view plaincopyprint?
//创建Application时同时创建的ContextIml实例
private final void handleBindApplication(AppBindData data){
...
///创建Application对象
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
...
}
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
...
try {
java.lang.ClassLoader cl = getClassLoader();
ContextImpl appContext = new ContextImpl(); //创建一个ContextImpl对象实例
appContext.init(this, null, mActivityThread); //初始化该ContextIml实例的相关属性
///新建一个Application对象
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app); //将该Application实例传递给该ContextImpl实例
}
...
}
2、创建Activity对象的时机
通过startActivity()或startActivityForResult()请求启动一个Activity时,如果系统检测需要新建一个Activity对象时,就会
回调handleLaunchActivity()方法,该方法继而调用performLaunchActivity()方法,去创建一个Activity实例,并且回调
onCreate(),onStart()方法等, 函数都位于 ActivityThread.java类 ,如下:
[java] view plaincopyprint?
//创建一个Activity实例时同时创建ContextIml实例
private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
...
Activity a = performLaunchActivity(r, customIntent); //启动一个Activity
}
private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
...
Activity activity = null;
try {
//创建一个Activity对象实例
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
}
if (activity != null) {
ContextImpl appContext = new ContextImpl(); //创建一个Activity实例
appContext.init(r.packageInfo, r.token, this); //初始化该ContextIml实例的相关属性
appContext.setOuterContext(activity); //将该Activity信息传递给该ContextImpl实例
...
}
...
}
3、创建Service对象的时机
通过startService或者bindService时,如果系统检测到需要新创建一个Service实例,就会回调handleCreateService()方法,
完成相关数据操作。handleCreateService()函数位于 ActivityThread.java类,如下:
[java] view plaincopyprint?
//创建一个Service实例时同时创建ContextIml实例
private final void handleCreateService(CreateServiceData data){
...
//创建一个Service实例
Service service = null;
try {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
service = (Service) cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
}
...
ContextImpl context = new ContextImpl(); //创建一个ContextImpl对象实例
context.init(packageInfo, null, this); //初始化该ContextIml实例的相关属性
//获得我们之前创建的Application对象信息
Application app = packageInfo.makeApplication(false, mInstrumentation);
//将该Service信息传递给该ContextImpl实例
context.setOuterContext(service);
...
}
另外,需要强调一点的是,通过对ContextImp的分析可知,其方法的大多数操作都是直接调用其属性mPackageInfo(该属性类
型为PackageInfo)的相关方法而来。这说明ContextImp是一种轻量级类,而PackageInfo才是真正重量级的类。而一个App里的
所有ContextIml实例,都对应同一个packageInfo对象。
最后给大家分析利用Context获取SharedPreferences类的使用方法,SharedPreferences类想必大家都使用过,其一般获取方
法就是通过调用getSharedPreferences()方法去根据相关信息获取SharedPreferences对象。具体流程如下:
1 、调用 getSharedPreferences()获取对应的的文件,该函数实现功能如下:
[java] view plaincopyprint?
//Context类静态数据集合,以键值对保存了所有读取该xml文件后所形成的数据集合
private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =
new HashMap<File, SharedPreferencesImpl>();
@Override
public SharedPreferences getSharedPreferences(String name, int mode){
//其所对应的SharedPreferencesImpl对象 ,该对象已一个HashMap集合保存了我们对该文件序列化结果
SharedPreferencesImpl sp;
File f = getSharedPrefsFile(name); //该包下是否存在对应的文件,不存在就新建一个
synchronized (sSharedPrefs) { //是否已经读取过该文件,是就直接返回该SharedPreferences对象
sp = sSharedPrefs.get(f);
if (sp != null && !sp.hasFileChanged()) {
//Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
return sp;
}
}
//以下为序列化该xml文件,同时将数据写到map集合中
Map map = null;
if (f.exists() && f.canRead()) {
try {
str = new FileInputStream(f);
map = XmlUtils.readMapXml(str);
str.close();
}
...
}
synchronized (sSharedPrefs) {
if (sp != null) {
//Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);
sp.replace(map); //更新数据集合
} else {
sp = sSharedPrefs.get(f);
if (sp == null) {
//新建一个SharedPreferencesImpl对象,并且设置其相关属性
sp = new SharedPreferencesImpl(f, mode, map);
sSharedPrefs.put(f, sp);
}
}
return sp;
}
}
2、 SharedPreferences 不过是个接口,它定义了一些操作xml文件的方法,其真正实现类为SharedPreferencesImpl ,该类是
ContextIml的内部类,该类如下:
[java] view plaincopyprint?
//soga,这种形式我们在分析Context ContextIml时接触过
//SharedPreferences只是一种接口,其真正实现类是SharedPreferencesImpl类
private static final class SharedPreferencesImpl implements SharedPreferences{
private Map mMap; //保存了该文件序列化结果后的操作, 键值对形式
//通过key值获取对应的value值
public String getString(String key, String defValue) {
synchronized (this) {
String v = (String)mMap.get(key);
return v != null ? v : defValue;
}
}
...
//获得该SharedPreferencesImpl对象对应的Edito类,对数据进行操作
public final class EditorImpl implements Editor {
private final Map<String, Object> mModified = Maps.newHashMap(); //保存了对键值变化的集合
}
}
基本上获取SharedPreferences 对象就是这么来的,关于Context里的更多方法请大家参照源代码认真学习吧。
Android中Context详解---- 你所不知道的Context
Android中Context详解---- 你所不知道的Context
前言:本文是我读《Android内核剖析》第7章 后形成的读书笔记,在此向欲了解Android框架的书籍推荐此书。
大家好, 今天给大家介绍下我们在应用开发中最熟悉而陌生的朋友-----Context类,说它熟悉,是应为我们在开发中
时刻的在与它打交道,例如:Service、BroadcastReceiver、Activity等都会利用到Context的相关方法 ;说它陌生,完全是
因为我们真正的不懂Context的原理、类结构关系。一个简单的问题是,一个应用程序App中存在多少个Context实例对象呢?
一个、两个? 在此先卖个关子吧。读了本文,相信您会豁然开朗的 。
Context,中文直译为“上下文”,SDK中对其说明如下:
Interfaceto global information about an application environment. This is anabstract class whose implementation
is provided by the Android system. It allows access toapplication-specific resources and classes, as well asup-calls
for application-level operations such as launching activities,broadcasting and receiving intents, etc
从上可知一下三点,即:
1、它描述的是一个应用程序环境的信息,即上下文。
2、该类是一个抽象(abstractclass)类,Android提供了该抽象类的具体实现类(后面我们会讲到是ContextIml类)。
3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别操作,例如:启动一个Activity,发送广播,接受Intent
信息 等。。
于是,我们可以利用该Context对象去构建应用级别操作(application-level operations)。
一、Context相关类的继承关系
相关类介绍:
Context类 路径:/frameworks/base/core/java/android/content/Context.java
说明: 抽象类,提供了一组通用的API。
源代码(部分)如下:
- public abstract class Context {
- ...
- public abstract Object getSystemService(String name); //获得系统级服务
- public abstract void startActivity(Intent intent); //通过一个Intent启动Activity
- public abstract ComponentName startService(Intent service); //启动Service
- //根据文件名得到SharedPreferences对象
- public abstract SharedPreferences getSharedPreferences(String name,int mode);
- ...
- }
ContextIml.java类 路径:/frameworks/base/core/java/android/app/ContextImpl.java
说明:该Context类的实现类为ContextIml,该类实现了Context类的功能。请注意,该函数的大部分功能都是直接调用
其属性mPackageInfo去完成,这点我们后面会讲到。
源代码(部分)如下:
- class ContextImpl extends Context{
- //所有Application程序公用一个mPackageInfo对象
- ActivityThread.PackageInfo mPackageInfo;
- @Override
- public Object getSystemService(String name){
- ...
- else if (ACTIVITY_SERVICE.equals(name)) {
- return getActivityManager();
- }
- else if (INPUT_METHOD_SERVICE.equals(name)) {
- return InputMethodManager.getInstance(this);
- }
- }
- @Override
- public void startActivity(Intent intent) {
- ...
- //开始启动一个Activity
- mMainThread.getInstrumentation().execStartActivity(
- getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
- }
- }
ContextWrapper类 路径:\frameworks\base\core\java\android\content\ContextWrapper.java
说明:正如其名称一样,该类只是对Context类的一种包装,该类的构造函数包含了一个真正的Context引用,即ContextIml
对象。 源代码(部分)如下:
- public class ContextWrapper extends Context {
- Context mBase; //该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
- //创建Application、Service、Activity,会调用该方法给mBase属性赋值
- protected void attachBaseContext(Context base) {
- if (mBase != null) {
- throw new IllegalStateException("Base context already set");
- }
- mBase = base;
- }
- @Override
- public void startActivity(Intent intent) {
- mBase.startActivity(intent); //调用mBase实例方法
- }
- }
ContextThemeWrapper类 路径:/frameworks/base/core/java/android/view/ContextThemeWrapper.java
说明:该类内部包含了主题(Theme)相关的接口,即android:theme属性指定的。只有Activity需要主题,Service不需要主题,
所以Service直接继承于ContextWrapper类。
源代码(部分)如下:
- public class ContextThemeWrapper extends ContextWrapper {
- //该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
- private Context mBase;
- //mBase赋值方式同样有一下两种
- public ContextThemeWrapper(Context base, int themeres) {
- super(base);
- mBase = base;
- mThemeResource = themeres;
- }
- @Override
- protected void attachBaseContext(Context newBase) {
- super.attachBaseContext(newBase);
- mBase = newBase;
- }
- }
Activity类 、Service类 、Application类本质上都是Context子类,更多信息大家可以自行参考源代码进行理解。
二、什么时候创建Context实例
熟悉了Context的继承关系后,我们接下来分析应用程序在什么情况需要创建Context对象的?应用程序创建Context实例的
情况有如下几种情况:
1、创建Application 对象时,而且整个App共一个Application对象
2、创建Service对象时
3、创建Activity对象时
因此应用程序App共有的Context数目公式为:
总Context实例个数 = Service个数 + Activity个数 +1(Application对应的Context实例)
具体创建Context的时机
1、创建Application对象的时机
每个应用程序在第一次启动时,都会首先创建Application对象。如果对应用程序启动一个Activity(startActivity)流程比较
清楚的话,创建Application的时机在创建handleBindApplication()方法中,该函数位于ActivityThread.java类中 ,如下:
- //创建Application时同时创建的ContextIml实例
- private final void handleBindApplication(AppBindData data){
- ...
- ///创建Application对象
- Application app = data.info.makeApplication(data.restrictedBackupMode, null);
- ...
- }
- public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
- ...
- try {
- java.lang.ClassLoader cl = getClassLoader();
- ContextImpl appContext = new ContextImpl(); //创建一个ContextImpl对象实例
- appContext.init(this, null, mActivityThread); //初始化该ContextIml实例的相关属性
- ///新建一个Application对象
- app = mActivityThread.mInstrumentation.newApplication(
- cl, appClass, appContext);
- appContext.setOuterContext(app); //将该Application实例传递给该ContextImpl实例
- }
- ...
- }
2、创建Activity对象的时机
通过startActivity()或startActivityForResult()请求启动一个Activity时,如果系统检测需要新建一个Activity对象时,就会
回调handleLaunchActivity()方法,该方法继而调用performLaunchActivity()方法,去创建一个Activity实例,并且回调
onCreate(),onStart()方法等,函数都位于 ActivityThread.java类 ,如下:
- //创建一个Activity实例时同时创建ContextIml实例
- private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity a = performLaunchActivity(r, customIntent); //启动一个Activity
- }
- private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity activity = null;
- try {
- //创建一个Activity对象实例
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
- }
- if (activity != null) {
- ContextImpl appContext = new ContextImpl(); //创建一个Activity实例
- appContext.init(r.packageInfo, r.token, this); //初始化该ContextIml实例的相关属性
- appContext.setOuterContext(activity); //将该Activity信息传递给该ContextImpl实例
- ...
- }
- ...
- }
3、创建Service对象的时机
通过startService或者bindService时,如果系统检测到需要新创建一个Service实例,就会回调handleCreateService()方法,
完成相关数据操作。handleCreateService()函数位于ActivityThread.java类,如下:
- //创建一个Service实例时同时创建ContextIml实例
- private final void handleCreateService(CreateServiceData data){
- ...
- //创建一个Service实例
- Service service = null;
- try {
- java.lang.ClassLoader cl = packageInfo.getClassLoader();
- service = (Service) cl.loadClass(data.info.name).newInstance();
- } catch (Exception e) {
- }
- ...
- ContextImpl context = new ContextImpl(); //创建一个ContextImpl对象实例
- context.init(packageInfo, null, this); //初始化该ContextIml实例的相关属性
- //获得我们之前创建的Application对象信息
- Application app = packageInfo.makeApplication(false, mInstrumentation);
- //将该Service信息传递给该ContextImpl实例
- context.setOuterContext(service);
- ...
- }
另外,需要强调一点的是,通过对ContextImp的分析可知,其方法的大多数操作都是直接调用其属性mPackageInfo(该属性类
型为PackageInfo)的相关方法而来。这说明ContextImp是一种轻量级类,而PackageInfo才是真正重量级的类。而一个App里的
所有ContextIml实例,都对应同一个packageInfo对象。
最后给大家分析利用Context获取SharedPreferences类的使用方法,SharedPreferences类想必大家都使用过,其一般获取方
法就是通过调用getSharedPreferences()方法去根据相关信息获取SharedPreferences对象。具体流程如下:
1 、调用 getSharedPreferences()获取对应的的文件,该函数实现功能如下:
- //Context类静态数据集合,以键值对保存了所有读取该xml文件后所形成的数据集合
- private static final HashMap sSharedPrefs =
- new HashMap();
- @Override
- public SharedPreferences getSharedPreferences(String name, int mode){
- //其所对应的SharedPreferencesImpl对象 ,该对象已一个HashMap集合保存了我们对该文件序列化结果
- SharedPreferencesImpl sp;
- File f = getSharedPrefsFile(name); //该包下是否存在对应的文件,不存在就新建一个
- synchronized (sSharedPrefs) { //是否已经读取过该文件,是就直接返回该SharedPreferences对象
- sp = sSharedPrefs.get(f);
- if (sp != null && !sp.hasFileChanged()) {
- //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
- return sp;
- }
- }
- //以下为序列化该xml文件,同时将数据写到map集合中
- Map map = null;
- if (f.exists() && f.canRead()) {
- try {
- str = new FileInputStream(f);
- map = XmlUtils.readMapXml(str);
- str.close();
- }
- ...
- }
- synchronized (sSharedPrefs) {
- if (sp != null) {
- //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);
- sp.replace(map); //更新数据集合
- } else {
- sp = sSharedPrefs.get(f);
- if (sp == null) {
- //新建一个SharedPreferencesImpl对象,并且设置其相关属性
- sp = new SharedPreferencesImpl(f, mode, map);
- sSharedPrefs.put(f, sp);
- }
- }
- return sp;
- }
- }
2、 SharedPreferences不过是个接口,它定义了一些操作xml文件的方法,其真正实现类为SharedPreferencesImpl,该类是
ContextIml的内部类,该类如下:
- //soga,这种形式我们在分析Context ContextIml时接触过
- //SharedPreferences只是一种接口,其真正实现类是SharedPreferencesImpl类
- private static final class SharedPreferencesImpl implements SharedPreferences{
- private Map mMap; //保存了该文件序列化结果后的操作, 键值对形式
- //通过key值获取对应的value值
- public String getString(String key, String defValue) {
- synchronized (this) {
- String v = (String)mMap.get(key);
- return v != null ? v : defValue;
- }
- }
- ...
- //获得该SharedPreferencesImpl对象对应的Edito类,对数据进行操作
- public final class EditorImpl implements Editor {
- private final Map mModified = Maps.newHashMap(); //保存了对键值变化的集合
- }
- }
基本上获取SharedPreferences对象就是这么来的,关于Context里的更多方法请大家参照源代码认真学习吧。
android中,下面代码中 public PlainView(Context context){,Context context是什么意思呢
import android.graphics.Matrix; import android.graphics.Paint; import android.view.View; /** 逻辑组件: * Created by dp on 2018/9/29. */ // 创建PlaneView public class PlainView extends View { public float currentX; public float currentY; Bitmap plane, plane1, plane2; public PlainView(Context context){ super(context); //飞机 = 来源 th_feiji plane = BitmapFactory.decodeResource(context.getResources(),R.drawable.th_feiji); //飞机1 = imgScale(th_feiji) plane = imageScale(plane, 160, 240); plane1=imageScale(plane, 60,80); //飞机2 = imgScale(th_feiji) plane2=imageScale(plane, 60,80); setFocusable(true); }
关于golang语言中的context详解,Go Concurrency Patterns: Context和golang context.done的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于.NET Core 中 WebOperationContext.Current.OutgoingResponse.ContentType 的替代方法是什么、Android中Context详解 ---- 你所不知道的Context、Android中Context详解---- 你所不知道的Context、android中,下面代码中 public PlainView(Context context){,Context context是什么意思呢等相关知识的信息别忘了在本站进行查找喔。
本文标签: