当前位置:网站首页>Network request -volley
Network request -volley
2022-06-25 00:25:00 【lcj908692】
Volley Is the use and interface
Say something else : about callback Concept and significance of . Wikipedia explains this : Pass a piece of code as a parameter , And this code will be run at some point ;
Personal understanding is : To keep the code clean . To make it easier to call and run something that is not in the same java Variables and functions in the file ; In order to make it easy to set aside an interface , It is convenient to add new functions later ;
/**
- Let's first introduce the functions of the three classes :
- Volley.java:Volley The main category of external exposure , adopt newRequestQueue(…) Function to create and start a request queue RequestQueue.
- Request: Requested abstract class .StringRequest、JsonRequest、ImageRequest It's all its subclasses , Represents a type of request . High scalability .
- RequestQueue.java: Request queue , It contains a CacheDispatcher( The scheduling thread used to process the cache request )、
NetworkDispatcher Array ( Scheduling thread used to process network requests ), One ResponseDelivery( Returns the result distribution interface ),
adopt start() When the function starts, it starts CacheDispatcher and NetworkDispatchers. - Then look back Volley The architecture of the figure .
- First step : Add the request to the cache queue
- The second step :「 Cache scheduling thread 」CacheDispatcher Take a request from the cache queue , If cache hits , Just read the cached response and parse , Then return the result to the main thread
- The third step : Cache miss , The request is added to the network request queue ,「 Network scheduling thread 」NetworkDispatcher Poll fetch request ,HTTP Request transmission , Parse response , Write cache , Then return the result to the main thread
*/
give an example :
public class MainActivity extends AppCompatActivity {
private static final String TAG = “lcj MainActivity”;
TextView requestNetTv;
TextView showNetContentTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
requestNetTv = findViewById(R.id.request_net);
showNetContentTv = findViewById(R.id.show_net_content);
requestNetTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// requestNet();
VolleyHttpUtils.requestNet(
“https://www.baidu.com”,
MainActivity.this,
new VolleyHttpUtils.OnHttpListener() { // Set listening
@Override
public void onResponse(String response) {
Log.i(TAG, “onResponse response:” + response);
Log.i(TAG, “onResponse threadName:” + Thread.currentThread().getName());
showNetContentTv.setText(response);
}
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, “onErrorResponse error:” + error.getMessage());
}
}
);
}
});
}
private void requestNet() {
// First step , utilize Volley new Come up with a request queue
RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
// The second step , Create a request
// ad locum , What we need to care about is whether the request is a success or a failure . Just these two points . It can be encapsulated with interfaces .
StringRequest stringRequest = new StringRequest(
“https://www.baidu.com”, // request url
new Response.Listener() { // Listening that returns the correct result
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, “ Successful visit ”, Toast.LENGTH_SHORT).show();
showNetContentTv.setText(response);
}
},
new Response.ErrorListener() { // Listening to return error results
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, “onErrorResponse error:” + error.getMessage());
}
});
// The third step , Put the request in the queue
mQueue.add(stringRequest);
}
}
public class VolleyHttpUtils {
private static final String TAG = “lcj VolleyHttpUtils”;
// In addition to the introduction of the necessary url And out of context , The key is to implement our interface , In this way, the outside world can easily explain the work to us
// We can't write things to death , You need to give the caller some freedom , What exactly does he want? Let him do it himself , Then the real work is still on our own
public static void requestNet(String url, Context context, final OnHttpListener onHttpListener) {
// First step : Create a queue
RequestQueue mQueue = Volley.newRequestQueue(context);
Log.i(TAG, “requestNet threadName:” + Thread.currentThread().getName());
// The second step : Create request object
StringRequest stringRequest = new StringRequest(url,
new Response.Listener() {
@Override
public void onResponse(String response) {
Log.i(TAG, “requestNet 2 threadName:” + Thread.currentThread().getName());
// The successful code of the external implementation interface about the request is actually executed here
onHttpListener.onResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// The external implementation interface tells the code about the failure of the request, which is actually executed here
onHttpListener.onErrorResponse(error);
}
});
// The third step : Add the request queue to the request queue
mQueue.add(stringRequest);
}
interface OnHttpListener {
void onResponse(String response);
void onErrorResponse(VolleyError error);
}
}
Print the results :
边栏推荐
- Ott marketing is booming. How should businesses invest?
- Adding, deleting, modifying and checking in low build code
- Analysis report on operation trend and investment strategy of global and Chinese tetrahydrofurfuryl propionate industry from 2022 to 2028
- Investment analysis and prospect forecast report of global and Chinese triglycine sulfate industry from 2022 to 2028
- Dynamic effect of canvas lines
- Current situation and development prospect forecast report of global and Chinese tetrahydrofurfuryl alcohol acetate industry from 2022 to 2028
- ros(25):rqt_image_view报错Unable to load plugin for transport ‘compressed‘, error string
- Wx applet jump page
- Transition from digitalization to intelligent manufacturing
- Encryption and encoding resolution
猜你喜欢
Paper review: U2 net, u-net composed of u-net

【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学

傳輸層 以字節為單比特的滑動窗口技術

Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)

Sliding window technology based on byte in transport layer

im即时通讯开发应用保活之进程防杀

【面试题】什么是事务,什么是脏读、不可重复读、幻读,以及MySQL的几种事务隔离级别的应对方法
Design and practice of vivo server monitoring architecture

Applet opening traffic master

Virtual machine - network configuration
随机推荐
【面试题】instancof和getClass()的区别
Helm chart仓库操作
Dynamic effect of canvas lines
What is test development? Can you find a job at this stage?
【面试题】什么是事务,什么是脏读、不可重复读、幻读,以及MySQL的几种事务隔离级别的应对方法
Microsoft won the title of "leader" in the magic quadrant of Gartner industrial Internet of things platform again!
Usage of assert
Basic summary of MySQL database knowledge
Im instant messaging development application keeping alive process anti kill
[leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
D manual destruction may violate memory security
Alternative to log4j
离散数学及其应用 2018-2019学年春夏学期期末考试 习题详解
不重要的token可以提前停止计算!英伟达提出自适应token的高效视觉Transformer网络A-ViT,提高模型的吞吐量!...
Uniapp encapsulated incentive advertisement, screen insert advertisement and banner advertisement
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
Analysis report on development trend and investment forecast of global and Chinese D-leucine industry from 2022 to 2028
JMeter socket connection sends data
ros(24):error: invalid initialization of reference of type ‘xx’ from expression of type ‘xx’