<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="likaihu.com.baway.monthexam_a.MainActivity">
<RadioGroup
android:id="@+id/RG"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_Introduce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="本社介绍"
android:textSize="20sp"
/>
<RadioButton
android:id="@+id/rb_ZhiNeng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="履行职能"
android:textSize="20sp"
/>
<RadioButton
android:id="@+id/rb_JianShe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="自身建设"
android:textSize="20sp"
/>
</RadioGroup>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:id="@+id/view_Introduce"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
<View
android:id="@+id/view_ZhiNeng"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
<View
android:id="@+id/view_JianShe"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
2.==========================================
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {
private ViewPager vp;
private RadioGroup rg;
private List<Fragment> fragmentList;
private RadioButton rb_introduce;
private RadioButton rb_zhiNeng;
private RadioButton rb_jianShe;
private View view_introduce;
private View view_zhiNeng;
private View view_jianShe;
private MyViewPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Boolean aBoolean = NetWorkUtils.netWorkIsConnection(this);
if (aBoolean){
initData();
initView();
//设置适配器
adapter = new MyViewPagerAdapter(getSupportFragmentManager(),fragmentList);
vp.setAdapter(adapter);
}else{
Toast.makeText(this,"没有网络,请连接网路!",Toast.LENGTH_SHORT).show();
//finish();
}
}
private void initView() {
vp = (ViewPager) findViewById(R.id.vp);
rg = (RadioGroup) findViewById(R.id.RG);
rb_introduce = (RadioButton) findViewById(R.id.rb_Introduce);
rb_zhiNeng = (RadioButton) findViewById(R.id.rb_ZhiNeng);
rb_jianShe = (RadioButton) findViewById(R.id.rb_JianShe);
view_introduce = findViewById(R.id.view_Introduce);
view_zhiNeng = findViewById(R.id.view_ZhiNeng);
view_jianShe = findViewById(R.id.view_JianShe);
rg.setOnCheckedChangeListener(this);
vp.setOnPageChangeListener(this);
}
private void initData() {
fragmentList = Arrays.asList(new FragmentIntroduce(), new FragmentZhiNeng(), new FragmentJianShe());
}
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int current = 0;
switch (checkedId) {
case R.id.rb_Introduce:
view_introduce.setVisibility(View.VISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
current = 0;
break;
case R.id.rb_ZhiNeng:
view_zhiNeng.setVisibility(View.VISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
current = 1;
break;
case R.id.rb_JianShe:
view_jianShe.setVisibility(View.VISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
current = 2;
break;
}
//判断是否是同一界面,不是则跳转指定页面
if (vp.getCurrentItem() != current) {
//vp.setCurrentItem(current);
vp.setCurrentItem(current, false);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
view_introduce.setVisibility(View.VISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
rb_introduce.setChecked(true);
break;
case 1:
view_zhiNeng.setVisibility(View.VISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
rb_zhiNeng.setChecked(true);
break;
case 2:
view_jianShe.setVisibility(View.VISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
rb_zhiNeng.setChecked(true);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
3.=========================================
public class StreamTools {
public static String parseStreamToString(InputStream is){
try {
int len =0;
byte[] buffer=new byte[1024];
ByteArrayOutputStream baos=new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
return baos.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4.========================================
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
try {
//缓存路径
File cacheDir = StorageUtils.getOwnCacheDirectory(this, Environment.getExternalStorageDirectory().getPath());
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
.threadPoolSize(3) //配置线程数
.memoryCache(new LruMemoryCache(2*1024*1024))//内存缓存图片 2M
.diskCache(new UnlimitedDiskCache(cacheDir))//配置sdcard的缓存路径
.diskCacheSize(50*1024*1024)//sdcard上缓存50M 的图片
.diskCacheFileCount(100)//缓存数量100个
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.build();
//配置缓存选项
ImageLoader.getInstance().init(configuration);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.=======================================
public class NetWorkUtils {
public static Boolean netWorkIsConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null){
return networkInfo.isAvailable();
}
return false;
}
}
6.==========================================
public class MyAdapter extends BaseAdapter {
private Context context;
private List<NewsInfo.DataBean> list;
//配置图片的缓存选项
private final DisplayImageOptions options;
public MyAdapter(Context context, List<NewsInfo.DataBean> list) {
this.context = context;
this.list = list;
options = new DisplayImageOptions.Builder().
cacheInMemory(true) //是否内存缓存
.cacheOnDisk(true)//是否sdcard缓存
.build();
}
@Override
public int getCount() {
return list != null ? list.size() : 0;
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder viewHolder = null;
if (convertView == null) {
convertView = convertView.inflate(context, R.layout.list_item01, null);
viewHolder = new viewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
viewHolder.ivZhiNeng = (ImageView) convertView.findViewById(R.id.iv_ZhiNeng);
convertView.setTag(viewHolder);
} else {
viewHolder = (MyAdapter.viewHolder) convertView.getTag();
}
viewHolder.ivZhiNeng.setImageResource(R.mipmap.ic_launcher);
viewHolder.tvTitle.setText(list.get(position).getTITLE());
viewHolder.tvContent.setText(list.get(position).getSUBTITLE());
//使用ImgeLoader加载图片,可以缓存
ImageLoader.getInstance().displayImage((String) list.get(position).getIMAGEURL(),viewHolder.ivZhiNeng,options);
return convertView;
}
static class viewHolder {
ImageView ivZhiNeng;
TextView tvTitle;
TextView tvContent;
}
}
7.==========================================
public class MyViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmnentList;
public MyViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmnentList=fragmentList;
}
@Override
public Fragment getItem(int position) {
return fragmnentList.get(position);
}
@Override
public int getCount() {
return fragmnentList !=null ? fragmnentList.size() :0;
}
}
8.=========================================
/**
* Created by TIGER LEE on 2017/4/27.
*/
public class FragmentZhiNeng extends Fragment {
private ListView lv_zhineng;
private NewsInfo newsInfo1;
private MyListViewAdapter adapter;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
lv_zhineng.setAdapter(adapter);
}
};
private FileInputStream input;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_zhineng, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv_zhineng = (ListView) getView().findViewById(R.id.lv_zhineng);
getInternetData("http://www.93.gov.cn/93app/data.do");
}
/**
* 获取网络数据
*/
public void getInternetData(String path) {
new AsyncTask<String, Void, String>() {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Gson gson = new Gson();
NewsInfo newsInfo = gson.fromJson(s, NewsInfo.class);
MyAdapter adapter = new MyAdapter(getContext(), newsInfo.getData());
lv_zhineng.setAdapter(adapter);
}
}
@Override
protected String doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5 * 1000);
connection.setConnectTimeout(5 * 1000);
OutputStream os = connection.getOutputStream();
os.write(("channelId=0&startNum=0").getBytes());
os.flush();
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = (InputStream) connection.getContent();
//通过工具解析流
String json = StreamTools.parseStreamToString(is);
//把json串写到sdcard中
writeDataToSdcard(is,json);
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(path);
}
public void writeDataToSdcard(InputStream is, String json) {
try {
File file = new File(Environment.getExternalStorageDirectory(), "newsinfo.txt");
OutputStream outputStream = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
} else {
outputStream.write(json.getBytes());
outputStream.flush();
is.close();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String readDataFromSdcard() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), "newsinfo.txt");
if (file.exists()) {
try {
input = new FileInputStream(file);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
return input.toString();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "sd 文件不存在", Toast.LENGTH_SHORT).show();
}
}else{
}
return input.toString();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="likaihu.com.baway.monthexam_a.MainActivity">
<RadioGroup
android:id="@+id/RG"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_Introduce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="本社介绍"
android:textSize="20sp"
/>
<RadioButton
android:id="@+id/rb_ZhiNeng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="履行职能"
android:textSize="20sp"
/>
<RadioButton
android:id="@+id/rb_JianShe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:padding="5dp"
android:text="自身建设"
android:textSize="20sp"
/>
</RadioGroup>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:id="@+id/view_Introduce"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
<View
android:id="@+id/view_ZhiNeng"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
<View
android:id="@+id/view_JianShe"
android:layout_width="100dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#E36257"
android:visibility="invisible"
></View>
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
2.==========================================
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {
private ViewPager vp;
private RadioGroup rg;
private List<Fragment> fragmentList;
private RadioButton rb_introduce;
private RadioButton rb_zhiNeng;
private RadioButton rb_jianShe;
private View view_introduce;
private View view_zhiNeng;
private View view_jianShe;
private MyViewPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Boolean aBoolean = NetWorkUtils.netWorkIsConnection(this);
if (aBoolean){
initData();
initView();
//设置适配器
adapter = new MyViewPagerAdapter(getSupportFragmentManager(),fragmentList);
vp.setAdapter(adapter);
}else{
Toast.makeText(this,"没有网络,请连接网路!",Toast.LENGTH_SHORT).show();
//finish();
}
}
private void initView() {
vp = (ViewPager) findViewById(R.id.vp);
rg = (RadioGroup) findViewById(R.id.RG);
rb_introduce = (RadioButton) findViewById(R.id.rb_Introduce);
rb_zhiNeng = (RadioButton) findViewById(R.id.rb_ZhiNeng);
rb_jianShe = (RadioButton) findViewById(R.id.rb_JianShe);
view_introduce = findViewById(R.id.view_Introduce);
view_zhiNeng = findViewById(R.id.view_ZhiNeng);
view_jianShe = findViewById(R.id.view_JianShe);
rg.setOnCheckedChangeListener(this);
vp.setOnPageChangeListener(this);
}
private void initData() {
fragmentList = Arrays.asList(new FragmentIntroduce(), new FragmentZhiNeng(), new FragmentJianShe());
}
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
int current = 0;
switch (checkedId) {
case R.id.rb_Introduce:
view_introduce.setVisibility(View.VISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
current = 0;
break;
case R.id.rb_ZhiNeng:
view_zhiNeng.setVisibility(View.VISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
current = 1;
break;
case R.id.rb_JianShe:
view_jianShe.setVisibility(View.VISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
current = 2;
break;
}
//判断是否是同一界面,不是则跳转指定页面
if (vp.getCurrentItem() != current) {
//vp.setCurrentItem(current);
vp.setCurrentItem(current, false);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
view_introduce.setVisibility(View.VISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
rb_introduce.setChecked(true);
break;
case 1:
view_zhiNeng.setVisibility(View.VISIBLE);
view_jianShe.setVisibility(View.INVISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
rb_zhiNeng.setChecked(true);
break;
case 2:
view_jianShe.setVisibility(View.VISIBLE);
view_introduce.setVisibility(View.INVISIBLE);
view_zhiNeng.setVisibility(View.INVISIBLE);
rb_zhiNeng.setChecked(true);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
3.=========================================
public class StreamTools {
public static String parseStreamToString(InputStream is){
try {
int len =0;
byte[] buffer=new byte[1024];
ByteArrayOutputStream baos=new ByteArrayOutputStream();
while((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
return baos.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4.========================================
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
try {
//缓存路径
File cacheDir = StorageUtils.getOwnCacheDirectory(this, Environment.getExternalStorageDirectory().getPath());
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
.threadPoolSize(3) //配置线程数
.memoryCache(new LruMemoryCache(2*1024*1024))//内存缓存图片 2M
.diskCache(new UnlimitedDiskCache(cacheDir))//配置sdcard的缓存路径
.diskCacheSize(50*1024*1024)//sdcard上缓存50M 的图片
.diskCacheFileCount(100)//缓存数量100个
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.build();
//配置缓存选项
ImageLoader.getInstance().init(configuration);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.=======================================
public class NetWorkUtils {
public static Boolean netWorkIsConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null){
return networkInfo.isAvailable();
}
return false;
}
}
6.==========================================
public class MyAdapter extends BaseAdapter {
private Context context;
private List<NewsInfo.DataBean> list;
//配置图片的缓存选项
private final DisplayImageOptions options;
public MyAdapter(Context context, List<NewsInfo.DataBean> list) {
this.context = context;
this.list = list;
options = new DisplayImageOptions.Builder().
cacheInMemory(true) //是否内存缓存
.cacheOnDisk(true)//是否sdcard缓存
.build();
}
@Override
public int getCount() {
return list != null ? list.size() : 0;
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder viewHolder = null;
if (convertView == null) {
convertView = convertView.inflate(context, R.layout.list_item01, null);
viewHolder = new viewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
viewHolder.ivZhiNeng = (ImageView) convertView.findViewById(R.id.iv_ZhiNeng);
convertView.setTag(viewHolder);
} else {
viewHolder = (MyAdapter.viewHolder) convertView.getTag();
}
viewHolder.ivZhiNeng.setImageResource(R.mipmap.ic_launcher);
viewHolder.tvTitle.setText(list.get(position).getTITLE());
viewHolder.tvContent.setText(list.get(position).getSUBTITLE());
//使用ImgeLoader加载图片,可以缓存
ImageLoader.getInstance().displayImage((String) list.get(position).getIMAGEURL(),viewHolder.ivZhiNeng,options);
return convertView;
}
static class viewHolder {
ImageView ivZhiNeng;
TextView tvTitle;
TextView tvContent;
}
}
7.==========================================
public class MyViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmnentList;
public MyViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmnentList=fragmentList;
}
@Override
public Fragment getItem(int position) {
return fragmnentList.get(position);
}
@Override
public int getCount() {
return fragmnentList !=null ? fragmnentList.size() :0;
}
}
8.=========================================
/**
* Created by TIGER LEE on 2017/4/27.
*/
public class FragmentZhiNeng extends Fragment {
private ListView lv_zhineng;
private NewsInfo newsInfo1;
private MyListViewAdapter adapter;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
lv_zhineng.setAdapter(adapter);
}
};
private FileInputStream input;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_zhineng, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv_zhineng = (ListView) getView().findViewById(R.id.lv_zhineng);
getInternetData("http://www.93.gov.cn/93app/data.do");
}
/**
* 获取网络数据
*/
public void getInternetData(String path) {
new AsyncTask<String, Void, String>() {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Gson gson = new Gson();
NewsInfo newsInfo = gson.fromJson(s, NewsInfo.class);
MyAdapter adapter = new MyAdapter(getContext(), newsInfo.getData());
lv_zhineng.setAdapter(adapter);
}
}
@Override
protected String doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5 * 1000);
connection.setConnectTimeout(5 * 1000);
OutputStream os = connection.getOutputStream();
os.write(("channelId=0&startNum=0").getBytes());
os.flush();
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = (InputStream) connection.getContent();
//通过工具解析流
String json = StreamTools.parseStreamToString(is);
//把json串写到sdcard中
writeDataToSdcard(is,json);
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(path);
}
public void writeDataToSdcard(InputStream is, String json) {
try {
File file = new File(Environment.getExternalStorageDirectory(), "newsinfo.txt");
OutputStream outputStream = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
} else {
outputStream.write(json.getBytes());
outputStream.flush();
is.close();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String readDataFromSdcard() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), "newsinfo.txt");
if (file.exists()) {
try {
input = new FileInputStream(file);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
return input.toString();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "sd 文件不存在", Toast.LENGTH_SHORT).show();
}
}else{
}
return input.toString();
}
}