com.jinrustar.sky.main.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.jinrustar.sky.main.MainActivity.java

Source

/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jinrustar.sky.main;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.jinrustar.sky.R;
import com.jinrustar.sky.adapter.MainFragmentPagerAdapter;
import com.jinrustar.sky.adapter.SearchAdapter;
import com.jinrustar.sky.config.Constants;
import com.jinrustar.sky.fragment.MainFragment;
import com.jinrustar.sky.model.DownloadVideoInfo;
import com.jinrustar.sky.model.VideoInfo;
import com.jinrustar.sky.tools.ApplicationConfig;
import com.jinrustar.sky.tools.GoloHandler;
import com.jinrustar.sky.tools.PreferencesManager;
import com.jinrustar.sky.tools.UpdateManager;
import com.jinrustar.sky.utils.WindowUtils;
import com.jinrustar.sky.view.SwitchButton;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.wlf.filedownloader.DownloadFileInfo;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.listener.OnFileDownloadStatusListener;
import org.wlf.filedownloader.listener.simple.OnSimpleFileDownloadStatusListener;
import org.wlf.filedownloader.util.FileUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.realm.Realm;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @Bind(R.id.viewpager)
    ViewPager mViewPager;
    @Bind(R.id.tabs)
    TabLayout mTabLayout;
    @Bind(R.id.nav_view)
    NavigationView mNavigationView;
    @Bind(R.id.fab)
    FloatingActionButton mFABtn;
    private Activity context;
    private Realm mRealm;
    private Bundle mReenterState;
    private MainFragmentPagerAdapter mPagerAdapter;
    private BenefitListFragment mBenefitListFragment;
    private List<VideoInfo> videoInfosAll = new ArrayList<VideoInfo>();
    private List<VideoInfo> videoInfosSong = new ArrayList<VideoInfo>();
    private List<VideoInfo> videoInfosModel = new ArrayList<VideoInfo>();
    private List<VideoInfo> videoInfosOrg = new ArrayList<VideoInfo>();
    public String content;
    Socket socket = null;
    BufferedWriter writer = null;
    BufferedReader reader = null;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                switch (msg.what) {
                case GoloHandler.CHAT_SELECT_PICTURE:
                    VideoInfo info = (VideoInfo) msg.obj;
                    itemClick(info);
                    break;
                case GoloHandler.CHAT_COMMON_BACK:
                    //                        title_layout_search.setVisibility(View.VISIBLE);
                    break;
                case GoloHandler.CHAT_COMMON_EDIT:
                    //                        title_layout_search.setVisibility(View.GONE);
                default:
                    break;
                }
            }
        }
    };
    long prelongTim = 0;
    long jiangeTime = 0;
    boolean firstClick = true;
    private int count = 0;
    public boolean isConnect = false;
    private int downloadid = 400;
    private DownloadVideoInfo downloadVideoInfo = null;
    private List<DownloadVideoInfo> downloadVideoInfos = null;

    private void itemClick(final int position) {
        if (prelongTim == 0) {//???
            prelongTim = System.currentTimeMillis();
        } else {
            long curTime = System.currentTimeMillis();
            ;//?
            jiangeTime = curTime - prelongTim;
            prelongTim = curTime;//???
        }
        if (jiangeTime > 5000 || firstClick) {
            firstClick = false;
            if (!TextUtils.isEmpty(content) && isConnect) {
                Log.i("ip", "ip_address:" + content);
                if (dialog == null)
                    dialog = new Dialog(context);
                dialog.getContext().setTheme(R.style.custom);
                dialog.setContentView(R.layout.layout_dialog_downloadtips);
                dialog.getWindow().setGravity(Gravity.CENTER);
                dialog.getWindow().setLayout(
                        dialog.getWindow().getWindowManager().getDefaultDisplay().getWidth() - 200,
                        WindowUtils.getScreenWidthAndHeight()[1] / 3);
                dialog.findViewById(R.id.tv_downloadcancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.findViewById(R.id.tv_download).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //                        search_layout.setVisibility(View.GONE);
                        //                        scan.setEnabled(true);
                        downloadVideoInfo = new DownloadVideoInfo();
                        downloadVideoInfo.setId(videoInfosAll.get(position).getId());
                        downloadid = videoInfosAll.get(position).getId();
                        downloadVideoInfo.setName(videoInfosAll.get(position).getName());
                        if (!isAdd(downloadVideoInfo.getId())) {
                            downloadVideoInfos.add(downloadVideoInfo);
                        } else {
                            dialog.dismiss();
                            return;
                        }
                        count++;
                        //                        Toast.makeText(context, "??id=" +videoInfosAll.get(position).getId()+videoInfosAll.get(position).getName(), Toast.LENGTH_SHORT).show();

                        sendmessage(videoInfosAll.get(position).getId() + "");
                        dialog.dismiss();
                    }
                });
                dialog.show();
                //                  showDownLoadDialog(videoInfos.get(position).getId() + "");

            } else {
                showDilogTips();
                Toast.makeText(context, "?????", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "????", Toast.LENGTH_SHORT).show();
        }
    }

    private void itemClick(final VideoInfo info) {
        if (prelongTim == 0) {//???
            prelongTim = System.currentTimeMillis();
        } else {
            long curTime = System.currentTimeMillis();
            ;//?
            jiangeTime = curTime - prelongTim;
            prelongTim = curTime;//???
        }
        if (jiangeTime > 5000 || firstClick) {
            firstClick = false;
            if (!TextUtils.isEmpty(content) && isConnect) {
                Log.i("ip", "ip_address:" + content);
                if (dialog == null)
                    dialog = new Dialog(context);
                dialog.getContext().setTheme(R.style.custom);
                dialog.setContentView(R.layout.layout_dialog_downloadtips);
                dialog.getWindow().setGravity(Gravity.CENTER);
                dialog.getWindow().setLayout(
                        dialog.getWindow().getWindowManager().getDefaultDisplay().getWidth() - 200,
                        WindowUtils.getScreenWidthAndHeight()[1] / 3);
                dialog.findViewById(R.id.tv_downloadcancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.findViewById(R.id.tv_download).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //                        search_layout.setVisibility(View.GONE);
                        //                        scan.setEnabled(true);
                        downloadVideoInfo = new DownloadVideoInfo();
                        downloadVideoInfo.setId(info.getId());
                        downloadid = info.getId();
                        downloadVideoInfo.setName(info.getName());
                        if (!isAdd(downloadVideoInfo.getId())) {
                            downloadVideoInfos.add(downloadVideoInfo);
                        } else {
                            dialog.dismiss();
                            return;
                        }
                        count++;
                        //                        Toast.makeText(context, "??id=" +info.getId()+info.getName(), Toast.LENGTH_SHORT).show();
                        sendmessage(info.getId() + "");
                        dialog.dismiss();
                    }
                });
                dialog.show();
                //                  showDownLoadDialog(videoInfos.get(position).getId() + "");

            } else {
                showDilogTips();
                Toast.makeText(context, "?????", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "????", Toast.LENGTH_SHORT).show();
        }
    }

    public void connect() {
        if (!TextUtils.isEmpty(content)) {
            AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        Log.i("connectIP:", content);
                        if (socket == null)
                            socket = new Socket(content, 2016);
                        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        publishProgress("@sucess");
                        String line;
                        while ((line = reader.readLine()) != null) {
                            publishProgress(line);
                        }
                    } catch (Exception e) {
                        isConnect = false;
                        //                        Constants._IP = content;
                        e.printStackTrace();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Looper.prepare();
                                Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        }).start();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... values) {
                    if (values[0].equals("@sucess")) {
                        isConnect = true;
                        Constants._IP = content;
                        Toast.makeText(context, "?", Toast.LENGTH_SHORT).show();
                    }
                    if (values[0].contains("http")) {
                        if (downloadid != 400 && downloadVideoInfos != null && downloadVideoInfos.size() > 0) {
                            downloadVideoInfos.get(count - 1).setUrl(values[0]);
                            String url = values[0];
                            //                            url = "http://www.x-ways.net/winhex/winhex.zip?t=123212421";
                            if (url.contains("?"))
                                url = url.split("\\?")[0];
                            FileDownloader.start(url);
                            Toast.makeText(context,
                                    url + "\n??",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    super.onProgressUpdate(values);
                }
            };
            read.execute();
        }
    }

    public void sendmessage(String id) {
        try {
            socket.sendUrgentData(0xFF);
        } catch (Exception e) {
            isConnect = false;
            connect();
            e.printStackTrace();
        }
        String uuid = PreferencesManager.getInstance(context).get(Constants.UUID,
                UUID.randomUUID().toString().replaceAll("-", ""));
        String orgin = PreferencesManager.getInstance(context).get(Constants.ORGINAL_ID, "1");
        id = id + ":" + uuid + ":" + orgin;
        try {
            writer.write(id + "\n");
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
            isConnect = false;
        }
    }

    private boolean isAdd(int id) {
        if (downloadVideoInfos == null)
            return false;
        for (int i = 0; i < downloadVideoInfos.size(); i++) {
            if (downloadVideoInfos.get(i).getId() == id) {
                Toast.makeText(context, "?", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    /***
     * ??????
     */
    //    private Observer<GoodsResult> getImageGoodsObserver = new Observer<GoodsResult>() {
    //        @Override
    //        public void onNext(final GoodsResult goodsResult) {
    //            if (null != goodsResult && null != goodsResult.getResults()) {
    //                ImageGoodsCache.getIns().addAllImageGoods(goodsResult.getResults());
    //            }
    //        }
    //
    //        @Override
    //        public void onCompleted() {
    //            Logger.d("???");
    //        }
    //
    //        @Override
    //        public void onError(final Throwable error) {
    //            Logger.e(error,"??");
    //        }
    //    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setAppVersion("2.0.6");
        CrashReport.initCrashReport(context, "900038709", false, strategy);
        //        CrashReport.testJavaCrash();
        ApplicationConfig.setAppInfo(context);
        setContentView(R.layout.activity_main);
        downloadVideoInfos = new ArrayList<DownloadVideoInfo>();
        FileDownloader.registerDownloadStatusListener(mOnFileDownloadStatusListener);

        mRealm = Realm.getInstance(this);

        ButterKnife.bind(this);
        ConfigStr = WindowUtils.getAssetsFileContent("main_layout_config.txt");
        setSupportActionBar(mToolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setCustomView(R.layout.title_layout);
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.getCustomView().findViewById(R.id.search_click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(content) || !isConnect) {
                    showDilogTips();
                    return;
                }
                Intent search = new Intent(context, SearchActivity.class);
                search.putExtra("vedioInfo", (Serializable) videoInfosSong);
                startActivityForResult(search, 0x88);
            }
        });
        ab.getCustomView().findViewById(R.id.scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDilogTips();
                //                Toast.makeText(MainActivity.this,"",Toast.LENGTH_SHORT).show();
            }
        });
        mFABtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent download = new Intent(context, MediaDownloadActivity.class);
                if (downloadVideoInfos != null && downloadVideoInfos.size() > 0) {
                    download.putExtra("downloadFlag", true);
                }
                if (videoInfosAll != null && videoInfosAll.size() > 0) {
                    download.putExtra("dowmloadinfo", (Serializable) videoInfosAll);
                }
                startActivity(download);
            }
        });

        setupDrawerContent(mNavigationView);
        setupViewPager();
        mTabLayout.setupWithViewPager(mViewPager);
        //        loadAllImageGoods();
    }

    Dialog dialog = null;

    private void showDilogTips() {
        if (dialog == null)
            dialog = new Dialog(context);
        dialog.getContext().setTheme(R.style.custom);
        dialog.setContentView(R.layout.layout_dialog_base);
        dialog.setTitle(R.string.toast_scan_tips);
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.getWindow().setLayout(dialog.getWindow().getWindowManager().getDefaultDisplay().getWidth() - 150,
                WindowUtils.getScreenWidthAndHeight()[1] / 2);
        dialog.findViewById(R.id.tv_title1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, QRScanActivity.class);
                startActivityForResult(intent, 0x57);
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.tv_title2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRealm.close();
    }

    private void getCacheData() {
        String str = PreferencesManager.getInstance(context).get(Constants.ORGINAL_DATA);
        if (TextUtils.isEmpty(str) || TextUtils.isEmpty(Constants._IP)) {
            initViewContent();
        } else {
            try {
                JSONObject object = new JSONObject(str);
                Log.i("net_str", str);
                String code = object.getString("v");
                //                    if (code.equals("1000")) {
                Log.i("net_videoinfos", "sucess");
                videoInfosSong.clear();
                JSONArray jsonArray = new JSONArray(object.getString("song"));
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    VideoInfo info = new VideoInfo();
                    info.setIcon(jsonObject.getString("image"));
                    info.setId(jsonObject.getInt("id"));
                    info.setName(jsonObject.getString("name"));
                    info.setPrice(jsonObject.getString("price"));
                    videoInfosSong.add(i, info);
                    Log.i("net_videoinfos",
                            videoInfosSong.get(i).getIcon() + "/" + videoInfosSong.get(i).getName());
                }
                JSONArray jsonArrayAll = new JSONArray(object.getString("all"));
                videoInfosAll.clear();
                for (int i = 0; i < jsonArrayAll.length(); i++) {
                    JSONObject jsonObject = jsonArrayAll.getJSONObject(i);
                    VideoInfo info = new VideoInfo();
                    info.setIcon(jsonObject.getString("image"));
                    info.setId(jsonObject.getInt("id"));
                    info.setName(jsonObject.getString("name"));
                    info.setPrice(jsonObject.getString("price"));
                    videoInfosAll.add(i, info);
                    Log.i("net_videoinfos_all",
                            videoInfosAll.get(i).getIcon() + "/" + videoInfosAll.get(i).getName());
                }
                JSONArray jsonArrayMod = new JSONArray(object.getString("scene"));
                videoInfosModel.clear();
                for (int i = 0; i < jsonArrayMod.length(); i++) {
                    JSONObject jsonObject = jsonArrayMod.getJSONObject(i);
                    VideoInfo info = new VideoInfo();
                    info.setIcon(jsonObject.getString("image"));
                    info.setId(jsonObject.getInt("id"));
                    info.setName(jsonObject.getString("name"));
                    info.setPrice(jsonObject.getString("price"));
                    videoInfosModel.add(i, info);
                    Log.i("net_videoinfos_scene",
                            videoInfosModel.get(i).getIcon() + "/" + videoInfosModel.get(i).getName());
                }
                JSONArray jsonArrayOrg = new JSONArray(object.getString("origin"));//origin
                videoInfosOrg.clear();
                for (int i = 0; i < jsonArrayOrg.length(); i++) {
                    JSONObject jsonObject = jsonArrayOrg.getJSONObject(i);
                    VideoInfo info = new VideoInfo();
                    info.setIcon(jsonObject.getString("image"));
                    info.setId(jsonObject.getInt("id"));
                    info.setName(jsonObject.getString("name"));
                    info.setPrice(jsonObject.getString("price"));
                    videoInfosOrg.add(i, info);
                    Log.i("net_videoinfos_origin",
                            videoInfosOrg.get(i).getIcon() + "/" + videoInfosOrg.get(i).getName());
                }
                //                    } else {
                //                        return;
                //                    }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private void setupViewPager() {
        getCacheData();
        //        mBenefitListFragment = new BenefitListFragment();
        mPagerAdapter = new MainFragmentPagerAdapter(getSupportFragmentManager());
        mPagerAdapter.addFragment(MainFragment.newInstance(videoInfosSong, "song"), "");
        mPagerAdapter.addFragment(MainFragment.newInstance(videoInfosModel, "scene"), "");
        mPagerAdapter.addFragment(MainFragment.newInstance(videoInfosOrg, "origin"), "");
        //        mPagerAdapter.addFragment(mBenefitListFragment, "?");
        mViewPager.setAdapter(mPagerAdapter);
    }

    private String ConfigStr;

    private void initViewContent() {
        if (!TextUtils.isEmpty(ConfigStr)) {
            try {
                JSONArray jsonArray = new JSONArray(ConfigStr);
                Log.i("jsonArray----", jsonArray.toString());
                int length = jsonArray.length();
                for (int i = 0; i < length; i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    VideoInfo info = new VideoInfo();
                    info.setIcon(jsonObject.getString("icon"));
                    info.setId(i);
                    info.setName(
                            getResources().getString(WindowUtils.getStringResId(jsonObject.getString("title"))));
                    info.setKey(jsonObject.getString("key"));
                    videoInfosSong.add(i, info);
                    videoInfosModel.add(i, info);
                    videoInfosOrg.add(i, info);
                    videoInfosAll.add(i, info);
                    Log.i("videoInfos1----",
                            videoInfosSong.get(i).getIcon() + "/" + videoInfosSong.get(i).getName());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (videoInfosAll != null) {
            Collections.sort(this.videoInfosAll, new SearchAdapter.SortRuleCollator());
        }
    }

    private void setupDrawerContent(NavigationView navigationView) {
        View view = navigationView.inflateHeaderView(R.layout.menu_layout);
        //        navigationView.getMenu().findItem(R.id.my_model).setChecked(true);
        view.findViewById(R.id.my_phote_layout).setOnClickListener(this);
        view.findViewById(R.id.my_model_layout).setOnClickListener(this);
        view.findViewById(R.id.my_download_layout).setOnClickListener(this);
        view.findViewById(R.id.my_about_layout).setOnClickListener(this);
        ((SwitchButton) view.findViewById(R.id.orignal_check))
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            PreferencesManager.getInstance(context).put(Constants.ORGINAL_ID, "1");
                        } else {
                            PreferencesManager.getInstance(context).put(Constants.ORGINAL_ID, "0");
                        }
                    }
                });
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                //                        menuItem.setChecked(false);
                mDrawerLayout.closeDrawers();
                //                        disposeMenuAction(menuItem);
                return true;
            }
        });
        //navigationView.findViewById(R.id.menu_header).setOnClickListener(new View.OnClickListener() {
        //    @Override
        //    public void onClick(View v) {
        //        callWebView(Constants.GANK_URL);
        //    }
        //});
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.my_phote_layout:
            Intent photo = new Intent(context, MediaDownloadActivity.class);
            photo.putExtra("pageFlag", "photo");
            startActivity(photo);
            mDrawerLayout.closeDrawers();
            break;
        case R.id.my_model_layout:
            mDrawerLayout.closeDrawers();
            break;
        case R.id.my_download_layout:
            Intent dload = new Intent(context, MediaDownloadActivity.class);
            dload.putExtra("downloadFlag", true);
            startActivity(dload);
            mDrawerLayout.closeDrawers();
            break;
        case R.id.my_about_layout:
            startActivity(new Intent(context, AboutUSActivity.class));
            mDrawerLayout.closeDrawers();
            break;
        case R.id.my_open_layout:
            mDrawerLayout.closeDrawers();
            break;
        }
    }

    //    private void disposeMenuAction(MenuItem item){
    //        switch (item.getItemId()){
    //            case R.id.my_photo:
    //                Intent photo = new Intent(context, MediaDownloadActivity.class);
    //                photo.putExtra("pageFlag","photo");
    //                startActivity(photo);
    //                break;
    //            case R.id.my_model:
    //                break;
    //            case R.id.my_download:
    //                Intent dload = new Intent(context, MediaDownloadActivity.class);
    //                dload.putExtra("downloadFlag",true);
    //                startActivity(dload);
    //                break;
    //            case R.id.about_us:
    //                startActivity(new Intent(context,AboutUSActivity.class));
    //                break;
    //            case R.id.open_org:
    //
    //                break;
    //        }
    //    }
    private Long firstTime = System.currentTimeMillis();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //            if(search_layout.getVisibility()==View.VISIBLE){
            //                search_layout.setVisibility(View.GONE);
            //                scan.setEnabled(true);
            //                return true;
            //            }
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, R.string.another_click_to_quit, Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                finish();
                System.exit(0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    //    private void loadAllImageGoods() {
    //        RealmResults<Image> allImage = mRealm.where(Image.class).findAll();
    //        if (allImage.size() == 0) {
    //            GankCloudApi.getIns()
    //                    .getBenefitsGoods(GankCloudApi.LOAD_LIMIT, 1)
    //                    .cache()
    //                    .subscribeOn(Schedulers.newThread())
    //                    .observeOn(AndroidSchedulers.mainThread())
    //                    .subscribe(getImageGoodsObserver);
    //        } else {
    //            ImageGoodsCache.getIns().addAllImageGoods(allImage);
    //        }
    //    }

    //    private SharedElementCallback mSharedElementCallback = new SharedElementCallback() {
    //        @Override
    //        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
    //            if (mReenterState != null) {
    //                int i = mReenterState.getInt("index", 0);
    //                sharedElements.clear();
    //                mBenefitListFragment.getActivitySharedElements(i,sharedElements);
    //                mReenterState = null;
    //            }
    //        }
    //    };
    //
    //    @Override
    //    public void onActivityReenter(int resultCode, Intent data) {
    //        super.onActivityReenter(resultCode, data);
    //        supportPostponeEnterTransition();
    //        mReenterState = new Bundle(data.getExtras());
    //        mBenefitListFragment.onActivityReenter(new Bundle(data.getExtras()));
    //    }

    private void callWebView(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    private OnFileDownloadStatusListener mOnFileDownloadStatusListener = new OnSimpleFileDownloadStatusListener() {
        @Override
        public void onFileDownloadStatusRetrying(DownloadFileInfo downloadFileInfo, int retryTimes) {
            // retrying download when failed once, the retryTimes is the current trying times
        }

        @Override
        public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {
            // waiting for download(wait for other tasks paused, or FileDownloader is busy for other operations)
        }

        @Override
        public void onFileDownloadStatusPreparing(DownloadFileInfo downloadFileInfo) {
            // preparing(connecting)
        }

        @Override
        public void onFileDownloadStatusPrepared(DownloadFileInfo downloadFileInfo) {
            // prepared(connected)
        }

        @Override
        public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo, float downloadSpeed,
                long remainingTime) {
            // downloading, the downloadSpeed with KB/s unit, the remainingTime with seconds unit
        }

        @Override
        public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {
            // download paused
        }

        @Override
        public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {
            // download completed(the url file has been finished)
            if ("zip".equalsIgnoreCase(FileUtil.getFileSuffix(downloadFileInfo.getFileName()))) {// apk
                String path = null;
                path = UpdateManager.sotrePath + "/" + downloadFileInfo.getFileName();
                UpdateManager um = new UpdateManager(context);
                um.doFileTask();
                um.unzipAndSave(path, UpdateManager.unZipPath);
                Toast.makeText(context,
                        downloadFileInfo.getFileName() + "??",
                        Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFileDownloadStatusFailed(String url, DownloadFileInfo downloadFileInfo,
                FileDownloadStatusFailReason failReason) {
            // error occur, see failReason for details, some of the failReason you must concern
            String msg = context.getString(R.string.main__download_error);

            if (failReason != null) {
                if (FileDownloadStatusFailReason.TYPE_NETWORK_DENIED.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__check_network);
                } else if (FileDownloadStatusFailReason.TYPE_URL_ILLEGAL.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__url_illegal);
                } else if (FileDownloadStatusFailReason.TYPE_NETWORK_TIMEOUT.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__network_timeout);
                } else if (FileDownloadStatusFailReason.TYPE_STORAGE_SPACE_IS_FULL.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__storage_space_is_full);
                } else if (FileDownloadStatusFailReason.TYPE_STORAGE_SPACE_CAN_NOT_WRITE
                        .equals(failReason.getType())) {
                    msg += context.getString(R.string.main__storage_space_can_not_write);
                } else if (FileDownloadStatusFailReason.TYPE_FILE_NOT_DETECT.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__file_not_detect);
                } else if (FileDownloadStatusFailReason.TYPE_BAD_HTTP_RESPONSE_CODE.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__http_bad_response_code);
                } else if (FileDownloadStatusFailReason.TYPE_HTTP_FILE_NOT_EXIST.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__http_file_not_exist);
                } else if (FileDownloadStatusFailReason.TYPE_SAVE_FILE_NOT_EXIST.equals(failReason.getType())) {
                    msg += context.getString(R.string.main__save_file_not_exist);
                }
            }

            if (downloadFileInfo == null) {
                //                showToast(msg + "url" + url);
                Toast.makeText(context, msg + "url" + url, Toast.LENGTH_SHORT).show();
                return;
            }

            //            String failType = failReason.getType();
            //            String failUrl = failReason.getUrl();// or failUrl = url, both url and failReason.getUrl() are the same
            //
            //            if(FileDownloadStatusFailReason.TYPE_URL_ILLEGAL.equals(failType)){
            //                // the url error when downloading file with failUrl
            //            }else if(FileDownloadStatusFailReason.TYPE_STORAGE_SPACE_IS_FULL.equals(failType)){
            //                // storage space is full when downloading file with failUrl
            //            }else if(FileDownloadStatusFailReason.TYPE_NETWORK_DENIED.equals(failType)){
            //                // network access denied when downloading file with failUrl
            //            }else if(FileDownloadStatusFailReason.TYPE_NETWORK_TIMEOUT.equals(failType)){
            //                // connect timeout when downloading file with failUrl
            //            }else{
            //                // more....
            //            }
            //
            //            // exception details
            //            Throwable failCause = failReason.getCause();// or failReason.getOriginalCause()
            //
            //            // also you can see the exception message
            //            String failMsg = failReason.getMessage();// or failReason.getOriginalCause().getMessage()
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x57 && resultCode == Activity.RESULT_OK) {
            content = data.getExtras().getString("result");
            if (!TextUtils.isEmpty(content)) {
                connect();
                //                Toast.makeText(context, "ip:"+content, Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == 0x88 && resultCode == Activity.RESULT_OK) {
            //            VideoInfo info = new VideoInfo();
            VideoInfo info = (VideoInfo) data.getExtras().getSerializable("videoinfo");
            itemClick(info);

        }
        if (requestCode == 0x55 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getColumnCount(); i++) {// ?uri???
                System.out.println(i + "-" + cursor.getColumnName(i) + "-" + cursor.getString(i));
            }
            //Intent
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            //              intent.setData(uri);
            startActivity(intent);
        } else if (requestCode == 0x56 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getColumnCount(); i++) {// ?uri???
                System.out.println(i + "-" + cursor.getColumnName(i) + "-" + cursor.getString(i));
            }
            //Intent
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "video/*");
            //             intent.setData(uri);
            startActivity(intent);
        }
    }
}