com.fangyuan.vpngate.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.fangyuan.vpngate.MainActivity.java

Source

/*
 * Copyright 2011 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.fangyuan.vpngate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ActionBarActivity {
    private Context mContext;
    private ListView mListView;
    private Handler mHandler;
    private ArrayList<HashMap<String, Object>> mListItems;

    private String hosts;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mContext = this;

        mListView = (ListView) findViewById(R.id.vpn_list);
        mListView.setDividerHeight(16);

        mListItems = new ArrayList<HashMap<String, Object>>();
        SimpleAdapter adapter = new SimpleAdapter(this, mListItems, R.layout.vpn_summary,
                new String[] { "country", "ip" }, new int[] { R.id.country, R.id.ip });
        mListView.setAdapter(adapter);

        hosts = getSharedPreferences("vpngate", MODE_PRIVATE).getString("hosts", null);
        if (hosts != null) {
            parseHostsString(hosts);
        }

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                hosts = msg.getData().getString("hosts");
                if (hosts != null) {
                    if (parseHostsString(hosts)) {
                        SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter();
                        adapter.notifyDataSetChanged();
                    }

                }
                getActionBarHelper().setRefreshActionItemState(false);
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);

        // Calling super after populating the menu is necessary here to ensure
        // that the
        // action bar helpers have a chance to handle this event.
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_refresh:
            refresh();
            break;

        case R.id.menu_setting:
            Intent intent = new Intent(this, SettingsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            String source = PreferenceManager.getDefaultSharedPreferences(mContext).getString("page_source",
                    mContext.getResources().getString(R.string.pref_default_source));
            URL url = null;
            HttpURLConnection urlConn = null;
            Bundle bunlde = new Bundle();
            Message msg = new Message();
            msg.setData(bunlde);
            try {
                url = new URL(source);
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setDoInput(true);
                urlConn.setDoOutput(true);
                urlConn.setUseCaches(false);
                urlConn.setConnectTimeout(10000);
                urlConn.setRequestMethod("GET");
                urlConn.connect();
                byte[] buffer = new byte[1024];
                InputStream is = urlConn.getInputStream();
                StringBuilder sb = new StringBuilder();
                int n = -1;
                while ((n = is.read(buffer)) != -1) {
                    sb.append(new String(buffer, 0, n, "UTF-8"));
                }

                bunlde.putString("hosts", sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConn != null) {
                    urlConn.disconnect();
                }
            }
            mHandler.sendMessage(msg);
        }
    };

    private void refresh() {
        getActionBarHelper().setRefreshActionItemState(true);
        new Thread(runnable).start();
    }

    private boolean parseHostsString(String hs) {
        JSONArray jsas;
        try {
            jsas = new JSONArray(hs);
            if (jsas != null) {
                mListItems.clear();
                int len = jsas.length();
                for (int i = 0; i < len; ++i) {
                    JSONArray jsa = jsas.getJSONArray(i);
                    if (jsa != null) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("country", jsa.get(0));
                        map.put("ip", jsa.get(1));
                        mListItems.add(map);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (hosts != null) {
            getSharedPreferences("vpngate", MODE_PRIVATE).edit().putString("hosts", hosts).commit();
        }
    }
}