com.intel.RtcPingDownloadTester.java Source code

Java tutorial

Introduction

Here is the source code for com.intel.RtcPingDownloadTester.java

Source

/*
 * INTEL CONFIDENTIAL
 * Copyright 2011
 * Intel Corporation All Rights Reserved.
 *
 * The source code contained or described herein and all documents
 * related to the source code ("Material") are owned by Intel
 * Corporation or its suppliers or licensors. Title to the Material
 * remains with Intel Corporation or its suppliers and licensors.
 * The Material contains trade secrets and proprietary and confidential
 * information of Intel or its suppliers and licensors. The Material is
 * protected by worldwide copyright and trade secret laws and treaty
 * provisions. No part of the Material may be used, copied, reproduced,
 * modified, published, uploaded, posted, transmitted, distributed, or
 * disclosed in any way without Intel's prior express written permission.
 *
 * No license under any patent, copyright, trade secret or other
 * intellectual property right is granted to or conferred upon you by
 * disclosure or delivery of the Materials, either expressly, by
 * implication, inducement, estoppel or otherwise. Any license under
 * such intellectual property rights must be express and approved by
 * Intel in writing.
 */

package com.intel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlarmManager;
import android.app.PendingIntent;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.IntentFilter;
import android.content.Context;
import android.content.BroadcastReceiver;

import android.os.AsyncResult;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.SystemClock;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

import android.telephony.TelephonyManager;

import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethod;

import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.CompoundButton;
import android.widget.CheckBox;

import android.text.method.DigitsKeyListener;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.text.format.Time;

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.File;

import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketTimeoutException;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.StatusLine;
import org.apache.http.HttpResponse;

import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.RILConstants;

public class RtcPingDownloadTester extends Activity {
    /** Called when the activity is first created. */
    WakeLock mWakeLock;
    WakeLock nWakeLock;
    private PendingIntent pendingIntent;
    private final String TAG = "intel";
    private Button b_Start;
    private Button b_Stop;
    private TextView label_curr_state;
    private TextView label_console_box;
    private EditText textBox_TimerEntry;
    private EditText textBox_HostIp;
    private EditText textBox_fileUrl;
    private EditText textBox_wklk;
    private CheckBox checkBox_1;
    private CheckBox checkBox_2;
    private CheckBox checkBox_3;
    public static final String ACTION_NAME = "com.intel.WAKEUP";
    private IntentFilter myFilter = new IntentFilter(ACTION_NAME);

    //parameters
    private boolean ping_enabled = false;
    private boolean download_enabled = false;
    private boolean wklk_enabled = false;
    private boolean ping_done = true;
    private boolean download_done = true;
    private boolean is_running = false;

    private String host_ip_addr = "192.168.1.1";
    private String fileUrl = "http://192.168.1.115/file.mp4";
    private String string_curr_state = "STOPED";
    private String string_console_text = "";

    private int full_lines = 0;
    private int nRepeatTimerEntry = 1;
    private int wklk = 5;

    BroadcastReceiver alarmReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v(TAG, "onReceive");
            update_conole_writeln("RTC trigger.");
            new setAlarmTask().execute(nRepeatTimerEntry * 1000);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy");
        mWakeLock = null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /** First, call the superclass onCreate method */
        super.onCreate(savedInstanceState);

        Log.v(TAG, "onCreate: " + savedInstanceState);

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RtcPingDownloadTester");
        nWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RtcPingDownloadTester2");
        setContentView(R.layout.main);

        b_Start = (Button) this.findViewById(R.id.ok);
        b_Start.setOnClickListener(new OnClickListener() {
            /* Start button pressed handler.*/
            public void onClick(View v) {
                Log.v(TAG, "onClick : START");

                /* a bit of sanity checking..*/
                if (nRepeatTimerEntry < 0)
                    nRepeatTimerEntry = 0;
                else if (nRepeatTimerEntry > 600)
                    nRepeatTimerEntry = 600;

                /* Entry point for alarm task */
                if ((nRepeatTimerEntry != 0) && (is_running == false)) {
                    is_running = true;
                    string_curr_state = "RUNNING";
                    label_curr_state.setText(string_curr_state);
                    registerReceiver(alarmReceiver, myFilter);
                    new setAlarmTask().execute(nRepeatTimerEntry * 1000);
                }
            }
        });

        b_Stop = (Button) this.findViewById(R.id.stop);
        b_Stop.setOnClickListener(new OnClickListener() {
            /* Stop button pressed handler*/
            public void onClick(View v) {
                Log.v(TAG, "onClick : STOP");
                if (is_running) {
                    unregisterReceiver(alarmReceiver);
                    is_running = false;
                    string_curr_state = "STOPED";
                    label_curr_state.setText(string_curr_state);
                    clearAlarm();
                }
            }
        });

        label_curr_state = (TextView) this.findViewById(R.id.label_curr_state);
        label_curr_state.setText(string_curr_state);

        label_console_box = (TextView) this.findViewById(R.id.label_console_box);
        label_console_box.setText(string_console_text);

        textBox_TimerEntry = (EditText) this.findViewById(R.id.textBox_1);
        textBox_TimerEntry.setText(String.valueOf(nRepeatTimerEntry), TextView.BufferType.EDITABLE);
        textBox_TimerEntry.addTextChangedListener(textBox_TimerEntry_EditorWatcher);

        textBox_HostIp = (EditText) this.findViewById(R.id.textBox_2);
        textBox_HostIp.setText(host_ip_addr, TextView.BufferType.EDITABLE);
        textBox_HostIp.addTextChangedListener(textBox_HostIp_EditorWatcher);

        textBox_fileUrl = (EditText) this.findViewById(R.id.textBox_3);
        textBox_fileUrl.setText(fileUrl, TextView.BufferType.EDITABLE);
        textBox_fileUrl.addTextChangedListener(textBox_fileUrl_EditorWatcher);

        textBox_wklk = (EditText) this.findViewById(R.id.textBox_4);
        textBox_wklk.setText(String.valueOf(wklk), TextView.BufferType.EDITABLE);
        textBox_wklk.addTextChangedListener(textBox_wklk_EditorWatcher);

        checkBox_1 = (CheckBox) this.findViewById(R.id.checkBox_1);
        checkBox_1.setChecked(ping_enabled);
        checkBox_1.setOnClickListener(new OnClickListener() {
            /* Ping checkbox handler */
            public void onClick(View v) {
                if (((CheckBox) v).isChecked())
                    ping_enabled = true;
                else
                    ping_enabled = false;
            }
        });

        checkBox_2 = (CheckBox) this.findViewById(R.id.checkBox_2);
        checkBox_2.setChecked(download_enabled);
        checkBox_2.setOnClickListener(new OnClickListener() {
            /* Download checkbox handler */
            public void onClick(View v) {
                if (((CheckBox) v).isChecked())
                    download_enabled = true;
                else
                    download_enabled = false;
            }
        });

        checkBox_3 = (CheckBox) this.findViewById(R.id.checkBox_3);
        checkBox_3.setChecked(wklk_enabled);
        checkBox_3.setOnClickListener(new OnClickListener() {
            /* Download checkbox handler */
            public void onClick(View v) {
                if (((CheckBox) v).isChecked())
                    wklk_enabled = true;
                else
                    wklk_enabled = false;
            }
        });

    } /* on_create */

    private final TextWatcher textBox_TimerEntry_EditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        /* Trigger textbox changed*/
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                nRepeatTimerEntry = Integer.parseInt(s.toString());
            } catch (Exception e) {
                Log.v(TAG, "textBox_TimerEntry_EditorWatcher Exception");
                nRepeatTimerEntry = 0;
            }
            ;
        }

        public void afterTextChanged(Editable s) {
        }
    };

    private final TextWatcher textBox_HostIp_EditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        /* Ping Textbox changed. */
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                host_ip_addr = s.toString();
            } catch (Exception e) {
                Log.v(TAG, "textBox_HostIp_EditorWatcher Exception");
                host_ip_addr = "192.168.1.1";
            }
            ;
        }

        public void afterTextChanged(Editable s) {
        }
    };

    private final TextWatcher textBox_fileUrl_EditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        /* File url textbox changed*/
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                fileUrl = s.toString();
            } catch (Exception e) {
                Log.v(TAG, "textBox_fileUrl_EditorWatcher Exception");
                fileUrl = "none";
            }
            ;
        }

        public void afterTextChanged(Editable s) {
        }
    };

    private final TextWatcher textBox_wklk_EditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        /* File url textbox changed*/
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                wklk = Integer.parseInt(s.toString());
            } catch (Exception e) {
                Log.v(TAG, "textBox_wklk_EditorWatcher Exception");
                wklk = 5;
            }
            ;
        }

        public void afterTextChanged(Editable s) {
        }
    };

    public void clearAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        Log.v(TAG, "clearAlarm");
        string_curr_state = "STOPED.";
        label_curr_state.setText(string_curr_state);
        return;
    }

    private void setAlarm(long millis) {
        Intent intent = new Intent(ACTION_NAME);
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Log.v(TAG, "setAlarm millis = " + millis);
        if (millis == 0)
            return;
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pendingIntent);
        return;
    }

    /* Manages the fake console box on UI. */
    private void update_conole_writeln(String line) {
        Time today = new Time(Time.getCurrentTimezone());
        today.setToNow();
        if (full_lines >= 10) {
            full_lines = 0;
            string_console_text = "";
        }
        full_lines++;
        string_console_text += today.format("%k:%M:%S") + ": " + line + "\n";
        label_console_box.setText(string_console_text);
    }

    /* Validate ip addres format from a string */
    public final boolean ValidateIPAddress(String ipAddress) {
        String[] parts = ipAddress.split("\\.");

        if (parts.length != 4)
            return false;

        for (String s : parts) {
            int i = 0;
            try {
                i = Integer.parseInt(s);
            } catch (Exception e) {
                return false;
            }

            if ((i < 0) || (i > 255))
                return false;
        }
        return true;
    }

    private int downloadFile(String url) {
        int statusCode = 0;
        try {
            HttpParams httpParams;
            FileOutputStream fos;
            httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
            HttpConnectionParams.setSoTimeout(httpParams, 1000);
            fos = new FileOutputStream(new File("/sdcard/down.dat"));
            HttpResponse response = new DefaultHttpClient(httpParams).execute(new HttpGet(url));
            statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200)
                response.getEntity().writeTo(fos);

        } catch (SocketTimeoutException e) {
            return -1;
        } catch (ConnectTimeoutException e) {
            return -1;
        } catch (Exception e) {
            return -1;
        }
        //return (int)(time2 - time1);
        return statusCode;
    }

    /* network operations cannot be done on UI thread so we use a task. */
    private int ping_host(String host) {
        InetAddress in = null;
        Log.v(TAG, "doInBackground");
        if (!ValidateIPAddress(host))
            return -1;
        try {
            Log.v(TAG, "InetAddress.getByName");
            in = InetAddress.getByName(host);
        } catch (UnknownHostException e) {
            Log.v(TAG, "UnknownHostException");
            return -1;
        }
        try {
            Log.v(TAG, "in.isReachable");
            if (in.isReachable(1000)) {
                return 1;
            } else
                return -1;
        } catch (IOException e) {
            return -1;
        }
    }

    private int hold_wklk() {
        //   nWakeLock.acquire(wklk * 1000);
        try {
            Thread.sleep(wklk * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /*cannot wait on UI for net opperations so wait on task*/
    private class setAlarmTask extends AsyncTask<Integer, String, Integer> {

        int ping_result = 0;
        int download_result = 0;
        int alarm_time = 0;
        int ping_time = 0;
        int download_time = 0;
        long time1 = 0;

        protected void onPreExecute() {
            mWakeLock.acquire();
        }

        protected Integer doInBackground(Integer... time) {
            alarm_time = time[0];
            time1 = System.currentTimeMillis();
            if (wklk_enabled)
                hold_wklk();
            if (ping_enabled)
                ping_result = ping_host(host_ip_addr);
            ping_time = (int) (System.currentTimeMillis() - time1);
            time1 = System.currentTimeMillis();

            if (download_enabled)
                download_result = downloadFile(fileUrl);
            download_time = (int) (System.currentTimeMillis() - time1);
            return 0;
        }

        protected void onPostExecute(Integer result) {
            /* Check ping results. */
            if ((ping_enabled) && (ping_result != -1))
                update_conole_writeln("Ping OK " + host_ip_addr + " " + ping_time + "ms");
            else if (ping_enabled)
                update_conole_writeln("Ping " + host_ip_addr + " fail");

            /* Check download results. */
            if ((download_enabled) && (download_result == 200))
                update_conole_writeln("D. OK " + download_time + "ms.");
            else if (download_enabled)
                update_conole_writeln("D. Err:" + download_result);

            if (wklk_enabled)
                update_conole_writeln("Wk. held: " + wklk + " sec");

            /* Set alarm again. */
            setAlarm(alarm_time);
            mWakeLock.release();
        }

    }
}