Please note that the contents of this offline web site may be out of date. To access the most recent documentation visit the online version .
Note that links that point to online resources are green in color and will open in a new window.
We would love it if you could give us feedback about this material by filling this form (You have to be online to fill it)
NetworkConnect / src / com.example.android.networkconnect /

MainActivity.java

       
        1
       
       
        /*
       
       
        2
       
       
        * Copyright 2013 The Android Open Source Project
       
       
        3
       
       
        *
       
       
        4
       
       
        * Licensed under the Apache License, Version 2.0 (the "License");
       
       
        5
       
       
        * you may not use this file except in compliance with the License.
       
       
        6
       
       
        * You may obtain a copy of the License at
       
       
        7
       
       
        *
       
       
        8
       
       
        *     http://www.apache.org/licenses/LICENSE-2.0
       
       
        9
       
       
        *
       
       
        10
       
       
        * Unless required by applicable law or agreed to in writing, software
       
       
        11
       
       
        * distributed under the License is distributed on an "AS IS" BASIS,
       
       
        12
       
       
        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       
       
        13
       
       
        * See the License for the specific language governing permissions and
       
       
        14
       
       
        * limitations under the License.
       
       
        15
       
       
        */
       
       
        16
       
       
       
       
        17
       
       
        package com.example.android.networkconnect;
       
       
        18
       
       
       
       
        19
       
       
        import android.os.AsyncTask;
       
       
        20
       
       
        import android.os.Bundle;
       
       
        21
       
       
        import android.support.v4.app.FragmentActivity;
       
       
        22
       
       
        import android.util.TypedValue;
       
       
        23
       
       
        import android.view.Menu;
       
       
        24
       
       
        import android.view.MenuItem;
       
       
        25
       
       
       
       
        26
       
       
        import com.example.android.common.logger.Log;
       
       
        27
       
       
        import com.example.android.common.logger.LogFragment;
       
       
        28
       
       
        import com.example.android.common.logger.LogWrapper;
       
       
        29
       
       
        import com.example.android.common.logger.MessageOnlyLogFilter;
       
       
        30
       
       
       
       
        31
       
       
        import java.io.IOException;
       
       
        32
       
       
        import java.io.InputStream;
       
       
        33
       
       
        import java.io.InputStreamReader;
       
       
        34
       
       
        import java.io.Reader;
       
       
        35
       
       
        import java.io.UnsupportedEncodingException;
       
       
        36
       
       
        import java.net.HttpURLConnection;
       
       
        37
       
       
        import java.net.URL;
       
       
        38
       
       
       
       
        39
       
       
        /**
       
       
        40
       
       
        * Sample application demonstrating how to connect to the network and fetch raw
       
       
        41
       
       
        * HTML. It uses AsyncTask to do the fetch on a background thread. To establish
       
       
        42
       
       
        * the network connection, it uses HttpURLConnection.
       
       
        43
       
       
        *
       
       
        44
       
       
        * This sample uses the logging framework to display log output in the log
       
       
        45
       
       
        * fragment (LogFragment).
       
       
        46
       
       
        */
       
       
        47
       
       
        public class MainActivity extends FragmentActivity {
       
       
        48
       
       
       
       
        49
       
       
        public static final String TAG = "Network Connect";
       
       
        50
       
       
       
       
        51
       
       
        // Reference to the fragment showing events, so we can clear it with a button
       
       
        52
       
       
        // as necessary.
       
       
        53
       
       
        private LogFragment mLogFragment;
       
       
        54
       
       
       
       
        55
       
       
        @Override
       
       
        56
       
       
        protected void onCreate(Bundle savedInstanceState) {
       
       
        57
       
       
        super.onCreate(savedInstanceState);
       
       
        58
       
       
        setContentView(R.layout.sample_main);
       
       
        59
       
       
       
       
        60
       
       
        // Initialize text fragment that displays intro text.
       
       
        61
       
       
        SimpleTextFragment introFragment = (SimpleTextFragment)
       
       
        62
       
       
        getSupportFragmentManager().findFragmentById(R.id.intro_fragment);
       
       
        63
       
       
        introFragment.setText(R.string.welcome_message);
       
       
        64
       
       
        introFragment.getTextView().setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16.0f);
       
       
        65
       
       
       
       
        66
       
       
        // Initialize the logging framework.
       
       
        67
       
       
        initializeLogging();
       
       
        68
       
       
        }
       
       
        69
       
       
       
       
        70
       
       
        @Override
       
       
        71
       
       
        public boolean onCreateOptionsMenu(Menu menu) {
       
       
        72
       
       
        getMenuInflater().inflate(R.menu.main, menu);
       
       
        73
       
       
        return true;
       
       
        74
       
       
        }
       
       
        75
       
       
       
       
        76
       
       
        @Override
       
       
        77
       
       
        public boolean onOptionsItemSelected(MenuItem item) {
       
       
        78
       
       
        switch (item.getItemId()) {
       
       
        79
       
       
        // When the user clicks FETCH, fetch the first 500 characters of
       
       
        80
       
       
        // raw HTML from www.google.com.
       
       
        81
       
       
        case R.id.fetch_action:
       
       
        82
       
       
        new DownloadTask().execute("http://www.google.com");
       
       
        83
       
       
        return true;
       
       
        84
       
       
        // Clear the log view fragment.
       
       
        85
       
       
        case R.id.clear_action:
       
       
        86
       
       
        mLogFragment.getLogView().setText("");
       
       
        87
       
       
        return true;
       
       
        88
       
       
        }
       
       
        89
       
       
        return false;
       
       
        90
       
       
        }
       
       
        91
       
       
       
       
        92
       
       
        /**
       
       
        93
       
       
        * Implementation of AsyncTask, to fetch the data in the background away from
       
       
        94
       
       
        * the UI thread.
       
       
        95
       
       
        */
       
       
        96
       
       
        private class DownloadTask extends AsyncTask<String, Void, String> {
       
       
        97
       
       
       
       
        98
       
       
        @Override
       
       
        99
       
       
        protected String doInBackground(String... urls) {
       
       
        100
       
       
        try {
       
       
        101
       
       
        return loadFromNetwork(urls[0]);
       
       
        102
       
       
        } catch (IOException e) {
       
       
        103
       
       
        return getString(R.string.connection_error);
       
       
        104
       
       
        }
       
       
        105
       
       
        }
       
       
        106
       
       
       
       
        107
       
       
        /**
       
       
        108
       
       
        * Uses the logging framework to display the output of the fetch
       
       
        109
       
       
        * operation in the log fragment.
       
       
        110
       
       
        */
       
       
        111
       
       
        @Override
       
       
        112
       
       
        protected void onPostExecute(String result) {
       
       
        113
       
       
        Log.i(TAG, result);
       
       
        114
       
       
        }
       
       
        115
       
       
        }
       
       
        116
       
       
       
       
        117
       
       
        /** Initiates the fetch operation. */
       
       
        118
       
       
        private String loadFromNetwork(String urlString) throws IOException {
       
       
        119
       
       
        InputStream stream = null;
       
       
        120
       
       
        String str ="";
       
       
        121
       
       
       
       
        122
       
       
        try {
       
       
        123
       
       
        stream = downloadUrl(urlString);
       
       
        124
       
       
        str = readIt(stream, 500);
       
       
        125
       
       
        } finally {
       
       
        126
       
       
        if (stream != null) {
       
       
        127
       
       
        stream.close();
       
       
        128
       
       
        }
       
       
        129
       
       
        }
       
       
        130
       
       
        return str;
       
       
        131
       
       
        }
       
       
        132
       
       
       
       
        133
       
       
        /**
       
       
        134
       
       
        * Given a string representation of a URL, sets up a connection and gets
       
       
        135
       
       
        * an input stream.
       
       
        136
       
       
        * @param urlString A string representation of a URL.
       
       
        137
       
       
        * @return An InputStream retrieved from a successful HttpURLConnection.
       
       
        138
       
       
        * @throws java.io.IOException
       
       
        139
       
       
        */
       
       
        140
       
       
        private InputStream downloadUrl(String urlString) throws IOException {
       
       
        142
       
       
        URL url = new URL(urlString);
       
       
        143
       
       
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       
       
        144
       
       
        conn.setReadTimeout(10000 /* milliseconds */);
       
       
        145
       
       
        conn.setConnectTimeout(15000 /* milliseconds */);
       
       
        146
       
       
        conn.setRequestMethod("GET");
       
       
        147
       
       
        conn.setDoInput(true);
       
       
        148
       
       
        // Start the query
       
       
        149
       
       
        conn.connect();
       
       
        150
       
       
        InputStream stream = conn.getInputStream();
       
       
        151
       
       
        return stream;
       
       
        153
       
       
        }
       
       
        154
       
       
       
       
        155
       
       
        /** Reads an InputStream and converts it to a String.
       
       
        156
       
       
        * @param stream InputStream containing HTML from targeted site.
       
       
        157
       
       
        * @param len Length of string that this method returns.
       
       
        158
       
       
        * @return String concatenated according to len parameter.
       
       
        159
       
       
        * @throws java.io.IOException
       
       
        160
       
       
        * @throws java.io.UnsupportedEncodingException
       
       
        161
       
       
        */
       
       
        162
       
       
        private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
       
       
        163
       
       
        Reader reader = null;
       
       
        164
       
       
        reader = new InputStreamReader(stream, "UTF-8");
       
       
        165
       
       
        char[] buffer = new char[len];
       
       
        166
       
       
        reader.read(buffer);
       
       
        167
       
       
        return new String(buffer);
       
       
        168
       
       
        }
       
       
        169
       
       
       
       
        170
       
       
        /** Create a chain of targets that will receive log data */
       
       
        171
       
       
        public void initializeLogging() {
       
       
        172
       
       
       
       
        173
       
       
        // Using Log, front-end to the logging chain, emulates
       
       
        174
       
       
        // android.util.log method signatures.
       
       
        175
       
       
       
       
        176
       
       
        // Wraps Android's native log framework
       
       
        177
       
       
        LogWrapper logWrapper = new LogWrapper();
       
       
        178
       
       
        Log.setLogNode(logWrapper);
       
       
        179
       
       
       
       
        180
       
       
        // A filter that strips out everything except the message text.
       
       
        181
       
       
        MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
       
       
        182
       
       
        logWrapper.setNext(msgFilter);
       
       
        183
       
       
       
       
        184
       
       
        // On screen logging via a fragment with a TextView.
       
       
        185
       
       
        mLogFragment =
       
       
        186
       
       
        (LogFragment) getSupportFragmentManager().findFragmentById(R.id.log_fragment);
       
       
        187
       
       
        msgFilter.setNext(mLogFragment.getLogView());
       
       
        188
       
       
        }
       
       
        189
       
       
        }