Android 数据传递的几种方式
一。用intent传递
第1个activity:
Intent intent =new Intent(this,TwoActivity.class); intent.putExtra("data",str); startActivity(intent);
第2个activity:
Intent intent=getIntnet(); String str=intent.getStringExtra("data")
二。使用bundle进行传值:
第1个activity:
Intentintent =new Intent(MainActivity.this,TwoActivity.class); Bundle bundle=new Bundle(); bundle.PutString("data",str); intent.putExtra("bun",bundle); startActivity(intent);
第2个activity:
Intent intent =getIntent(); bundle bundle=inteent.getBundlePutExtra("bun"); String str =Bundle.getString("data"); tv.setText();
三。当antivity销毁时传递数据StartActivityForResult
第1个activity:
Intent intent =new Intent(MainActivity.this,TwoActivity.this); StartActivityForResult(intent,1111) protected viod onActivityResult(int requestCode,int resultCode,Intent data){ super.onActivityResult(request,resultCode,data); String str=data.getStringExtra("data") tv.setText(str); }
第2个activity:
Intent intent =new Intent(); intent.putExtra("data",)
HttpLoggingInterceptor消息拦截器
使用原因:
利用了消息拦截器可以清楚的看到接口返回的所有内容。不需要重新使用fildder等抓包工具来做分析。
1.添加依赖
//okhttp的log信息 compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
2.在合适的位置初始化(这里放在了构造,因为是单例,响应的拦截器也只new一次)
private HttpMethod() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { try { String text = URLDecoder.decode(message, "utf-8"); Log.e("OKHttp-----", text); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("OKHttp-----", message); } } }); //这里可以builder(). 添加更多的内容 具体看需求 mClient = new OkHttpClient.Builder().addInterceptor(interceptor).build(); //这行必须加 不然默认不打印 interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); }
3.在retrofit中设置httpclient
Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加HttpClient .client(mClient) .build(); mApiService = retrofit.create(ApiService.class);
setlevel用来设置日志打印的级别,共包括了四个级别:NONE,BASIC,HEADER,BODY
- BASEIC:请求/响应行
- HEADER:请求/响应行 + 头
- BODY:请求/响应航 + 头 + 体