Browse Source

Initial commit. It's version 1.3.1

Signed-off-by: Carlos Silva <r3pek@r3pek.org>
master
Carlos Mogas da Silva 9 years ago
commit
9346ea10e5

+ 8
- 0
.classpath View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="lib" path="libs/admob-sdk-android.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
/gen

+ 33
- 0
.project View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>DroidUptime</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

+ 31
- 0
AndroidManifest.xml View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.r3pek.droiduptime"
android:versionName="1.3.1" android:versionCode="7">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="false">


<service android:name="DroidUptimeService"></service>
<receiver android:name="DroidUptimeServiceManager">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<activity android:name="Main" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity>
<meta-data android:value="a14bad01161834d" android:name="ADMOB_PUBLISHER_ID" />
<activity android:name="MyPreferences"></activity>
</application>
<uses-sdk android:minSdkVersion="3"/>

<supports-screens android:resizeable="true" android:largeScreens="true" android:anyDensity="false" android:normalScreens="true" android:smallScreens="true"></supports-screens>


<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
</manifest>

BIN
bin/DroidUptime.apk View File


BIN
bin/classes.dex View File


BIN
bin/resources.ap_ View File


+ 13
- 0
default.properties View File

@@ -0,0 +1,13 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.

# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
target=android-4

BIN
libs/admob-sdk-android.jar View File


BIN
res/drawable-mdpi/droiduptime.png View File


BIN
res/drawable-mdpi/icon.png View File


+ 8
- 0
res/layout/about.xml View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/aboutRoot">
<LinearLayout android:id="@+id/LinearLayout02" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center" android:layout_width="fill_parent"><ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dip" android:textSize="20dip" android:text="@string/app_name"></TextView>
</LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/about" android:gravity="center" android:id="@+id/tvAbout" android:layout_marginBottom="20dip" android:layout_marginTop="20dip" android:autoLink="web"></TextView>
</LinearLayout>

+ 38
- 0
res/layout/main.xml View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/org.r3pek.droiduptime"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">



<com.admob.android.ads.AdView android:layout_gravity="bottom" android:id="@+id/ad" android:layout_width="fill_parent" android:layout_alignParentBottom="true" myapp:backgroundColor="#000000" myapp:primaryTextColor="#FFFFFF" myapp:secondaryTextColor="#CCCCCC" android:layout_height="wrap_content" />
<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/droiduptime" android:layout_gravity="center_horizontal" android:layout_marginTop="20dip"></ImageView>

<TableLayout android:id="@+id/TableLayout01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:stretchColumns="1" android:paddingTop="20dip">
<TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
<LinearLayout android:id="@+id/LinearLayout01" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_width="fill_parent">
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_marginTop="15dip" android:text="@string/servicestatus"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dip" android:id="@+id/tvStatus" android:layout_marginTop="15dip"></TextView>
</LinearLayout>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnStartStopService" android:layout_gravity="right"></Button>
</TableRow>
</TableLayout>


<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingTop="10dip"><TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/uptime"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dip" android:id="@+id/tvUptime"></TextView>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="15dip"><TextView android:id="@+id/TextView06" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="@string/lastupdate"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dip" android:id="@+id/tvLastUpdate"></TextView>
</LinearLayout><TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dip" android:linksClickable="true" android:autoLink="web" android:text="@string/message"></TextView>


</LinearLayout>
</ScrollView>

+ 46
- 0
res/values-en/strings.xml View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DroidUptime</string>
<string name="about">DroidUptime application was developed by Carlos Silva and uses www.uptimeprj.com to commit the uptime information. If you liked this application, and if you want to, feel free to make a donation at www.r3pek.org or the Uptime Project website. Thanks.</string>
<string name="status_running">Running</string>
<string name="status_stopped">Stopped</string>
<string name="operation_start">Start</string>
<string name="operation_stop">Stop</string>
<string name="menu_about">About</string>
<string name="menu_setup">Setup</string>
<string name="btn_ok">OK</string>
<string name="btn_cancel">Cancel</string>
<string name="servicestatus">Service Status:</string>
<string name="uptime">Uptime:</string>
<string name="lastupdate">Last Update:</string>
<string name="message">This application requires you to register at www.uptimeprj.com so you can keep track of your uptime. After you registered, come back here and fill in the username and password on the Setup Menu.</string>
<string name="notyetupdated">Haven't updated yet</string>
<string name="months">months</string>
<string name="days">days</string>
<string name="hours">hours</string>
<string name="minutes">minutes and</string>
<string name="seconds">seconds</string>
<string name="pref_auth_cat">Authentication</string>
<string name="pref_auth_user">Username</string>
<string name="pref_auth_pass">Password</string>
<string name="pref_gen_cat">General</string>
<string-array name="update_intervals">
<item>10 Minutes</item>
<item>20 Minutes</item>
<item>30 Minutes</item>
<item>1 Hour</item>
<item>2 Hours</item>
</string-array>
<string name="pref_gen_update_int">Update Interval</string>
<string name="pref_gen_update_int_desc">How often it will submit the uptime (requires restart of the service)</string>
<string-array name="update_intervals_values">
<item>600</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
<item>7200</item>
</string-array>
<string name="no_user_pass">Please setup Username and Password</string>
<string name="pref_gen_hostname">Hostname</string>
<string name="pref_gen_hostname_desc">Hostname to send to the Uptime Project</string>
</resources>

+ 46
- 0
res/values-es/strings.xml View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DroidUptime</string>
<string name="about">La aplicación DroidUptime fué desarrollada por Carlos Silva y usa www.uptimeprj.com para recojer la información de uptime. Si te gusta esta aplicación, y si te apetece puede enviar tu donativo para www.r3pek.org o all Uptime Project website. Gracias.</string>
<string name="status_running">En ejecución</string>
<string name="status_stopped">Parado</string>
<string name="operation_start">Empezar</string>
<string name="operation_stop">Parar</string>
<string name="menu_about">Sobre</string>
<string name="menu_setup">Configuración</string>
<string name="btn_ok">Aceptar</string>
<string name="btn_cancel">Cancelar</string>
<string name="servicestatus">Estado:</string>
<string name="uptime">Tiempo actividad:</string>
<string name="lastupdate">Ultima actualización:</string>
<string name="message">Tienes que registrarte en www.uptimeprj.com para que puedas saber tu uptime. Después del registro coloca tus datos en el menu de configuración.</string>
<string name="notyetupdated">Sin actualizar</string>
<string name="months">Meses</string>
<string name="days">días</string>
<string name="hours">horas</string>
<string name="minutes">minutos y</string>
<string name="seconds">segundos</string>
<string name="pref_auth_cat">Autenticación</string>
<string name="pref_auth_user">Usuário</string>
<string name="pref_auth_pass">Contraseña</string>
<string name="pref_gen_cat">General</string>
<string-array name="update_intervals">
<item>10 Minutos</item>
<item>20 Minutos</item>
<item>30 Minutos</item>
<item>1 Hora</item>
<item>2 Horas</item>
</string-array>
<string name="pref_gen_update_int">Intervalo de actualización</string>
<string name="pref_gen_update_int_desc">A cada cuanto tiempo quieres que se actualice. (necesitas reiniciar el servicio)</string>
<string-array name="update_intervals_values">
<item>600</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
<item>7200</item>
</string-array>
<string name="no_user_pass">Por favor configura el usuário y contraseña</string>
<string name="pref_gen_hostname">Nombre del equipo</string>
<string name="pref_gen_hostname_desc">Nombre del equipo para Uptime Project</string>
</resources>

+ 46
- 0
res/values-pt/strings.xml View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DroidUptime</string>
<string name="about">A aplicação DroidUptime foi desenvolvida por Carlos Silva e usa o site www.uptimeprj.com para guardar a informação relativa ao uptime. Se gostou desta aplicação, e se quiser, faça um donativo em www.r3pek.org ou no site do Uptime Project. Obrigado.</string>
<string name="status_running">A executar</string>
<string name="status_stopped">Parado</string>
<string name="operation_start">Iniciar</string>
<string name="operation_stop">Parar</string>
<string name="menu_about">Sobre</string>
<string name="menu_setup">Configuração</string>
<string name="btn_ok">OK</string>
<string name="btn_cancel">Cancelar</string>
<string name="servicestatus">Estado do Serviço:</string>
<string name="uptime">Uptime:</string>
<string name="lastupdate">Última actualização:</string>
<string name="message">Esta aplicação necessita que se registe em www.uptimeprj.com para que se possa guardar e para controlar o seu uptime. Após o registo, volte a esta aplicação e preencha o Utilizador e a Senha no menu Configuração.</string>
<string name="notyetupdated">Ainda não actualizado</string>
<string name="months">meses</string>
<string name="days">dias</string>
<string name="hours">horas</string>
<string name="minutes">minutos e</string>
<string name="seconds">segundos</string>
<string name="pref_auth_cat">Autenticação</string>
<string name="pref_auth_user">Utilizador</string>
<string name="pref_auth_pass">Senha</string>
<string name="pref_gen_cat">Geral</string>
<string-array name="update_intervals">
<item>10 Minutos</item>
<item>20 Minutos</item>
<item>30 Minutos</item>
<item>1 Hora</item>
<item>2 Horas</item>
</string-array>
<string name="pref_gen_update_int">Frequência das Actualizações</string>
<string name="pref_gen_update_int_desc">Frequência em que o uptime é submetido ao servidor (requer que se reinicie o serviço)</string>
<string-array name="update_intervals_values">
<item>600</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
<item>7200</item>
</string-array>
<string name="no_user_pass">Insira o utilizador e a senha no menu configuração</string>
<string name="pref_gen_hostname">Hostname</string>
<string name="pref_gen_hostname_desc">Hostname a reportar para o Uptime Project</string>
</resources>

+ 46
- 0
res/values-zh-rCN/strings.xml View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DroidUptime</string>
<string name="about">DroidUptime 应用是由 Carlos Silva 根据 www.uptimeprj.com 的正常运行时间数据开发的。如果您喜欢这个应用请到 www.r3pek.org 或 Uptime 项目的主页捐助, 谢谢!</string>
<string name="status_running">运行中</string>
<string name="status_stopped">已停止</string>
<string name="operation_start">开始</string>
<string name="operation_stop">停止</string>
<string name="menu_about">关于</string>
<string name="menu_setup">设置</string>
<string name="btn_ok">确定</string>
<string name="btn_cancel">取消</string>
<string name="servicestatus">服务状态:</string>
<string name="uptime">正常运行时间:</string>
<string name="lastupdate">最近更新:</string>
<string name="message">该应用需要注册, www.uptimeprj.com 这样您就可以跟踪您的正常运行时间。 注册完之后请回到这里并在设置菜单中填写用户名和密码。</string>
<string name="notyetupdated">还没有更新</string>
<string name="months">月</string>
<string name="days">日</string>
<string name="hours">时</string>
<string name="minutes">分和</string>
<string name="seconds">秒</string>
<string name="pref_auth_cat">验证</string>
<string name="pref_auth_user">用户名</string>
<string name="pref_auth_pass">密码</string>
<string name="pref_gen_cat">概况General</string>
<string-array name="update_intervals">
<item>10 分钟</item>
<item>20 分钟</item>
<item>30 分钟</item>
<item>1 小时</item>
<item>2 小时</item>
</string-array>
<string name="pref_gen_update_int">更新间隔</string>
<string name="pref_gen_update_int_desc">多久提交更新 (需重启该服务)</string>
<string-array name="update_intervals_values">
<item>600</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
<item>7200</item>
</string-array>
<string name="no_user_pass">请设定用户名和密码</string>
<string name="pref_gen_hostname">主机名</string>
<string name="pref_gen_hostname_desc">主机名发送到 Uptime 项目</string>
</resources>

+ 46
- 0
res/values-zh-rTW/strings.xml View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DroidUptime</string>
<string name="about">DroidUptime 套用是由 Carlos Silva 依 www.uptimeprj.com 的正常執行時間資料開發的。如果您喜歡這個套用請到 www.r3pek.org 或 Uptime 項目的首頁捐助, 謝謝!</string>
<string name="status_running">執行中</string>
<string name="status_stopped">已停止</string>
<string name="operation_start">開始</string>
<string name="operation_stop">停止</string>
<string name="menu_about">關於</string>
<string name="menu_setup">設定</string>
<string name="btn_ok">確定</string>
<string name="btn_cancel">取消</string>
<string name="servicestatus">服務狀態:</string>
<string name="uptime">正常執行時間:</string>
<string name="lastupdate">最近更新:</string>
<string name="message">該套用需要註冊, www.uptimeprj.com 這樣您就可以跟蹤您的正常執行時間。 註冊完之後請回到這裡並在設定功能表中填寫使用者名稱和密碼。</string>
<string name="notyetupdated">還沒有更新</string>
<string name="months">月</string>
<string name="days">日</string>
<string name="hours">時</string>
<string name="minutes">分和</string>
<string name="seconds">秒</string>
<string name="pref_auth_cat">驗證</string>
<string name="pref_auth_user">使用者名稱</string>
<string name="pref_auth_pass">密碼</string>
<string name="pref_gen_cat">概況General</string>
<string-array name="update_intervals">
<item>10 分鐘</item>
<item>20 分鐘</item>
<item>30 分鐘</item>
<item>1 小時</item>
<item>2 小時</item>
</string-array>
<string name="pref_gen_update_int">更新間隔</string>
<string name="pref_gen_update_int_desc">多久提交更新 (需重啟該服務)</string>
<string-array name="update_intervals_values">
<item>600</item>
<item>1200</item>
<item>1800</item>
<item>3600</item>
<item>7200</item>
</string-array>
<string name="no_user_pass">請設定使用者名稱和密碼</string>
<string name="pref_gen_hostname">主機名</string>
<string name="pref_gen_hostname_desc">主機名發送到 Uptime 項目</string>
</resources>

+ 10
- 0
res/values/attrs.xml View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="com.admob.android.ads.AdView">
<attr name="backgroundColor" format="color" />
<attr name="primaryTextColor" format="color" />
<attr name="secondaryTextColor" format="color" />
<attr name="keywords" format="string" />
<attr name="refreshInterval" format="integer" />
</declare-styleable>
</resources>

+ 13
- 0
res/xml/preferences.xml View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="preferences">
<PreferenceCategory android:title="@string/pref_auth_cat" android:key="auth">
<EditTextPreference android:key="username" android:title="@string/pref_auth_user"></EditTextPreference>
<EditTextPreference android:key="password" android:title="@string/pref_auth_pass" android:password="true" ></EditTextPreference>
</PreferenceCategory>
<PreferenceCategory android:key="general" android:title="@string/pref_gen_cat">
<ListPreference android:entries="@array/update_intervals" android:key="pref_gen_update_int" android:summary="@string/pref_gen_update_int_desc" android:title="@string/pref_gen_update_int" android:entryValues="@array/update_intervals_values"></ListPreference>
<EditTextPreference android:summary="@string/pref_gen_hostname_desc" android:title="@string/pref_gen_hostname" android:key="pref_gen_hostname"></EditTextPreference>
</PreferenceCategory>
</PreferenceScreen>

+ 575
- 0
src/org/r3pek/droiduptime/Base64.java View File

@@ -0,0 +1,575 @@
package org.r3pek.droiduptime;
import java.util.Arrays;
/** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
* with RFC 2045.<br><br>
* On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
* on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
* compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
*
* On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
* about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
* arrays (&lt 30 bytes). If source/destination is a <code>String</code> this
* version is about three times as fast due to the fact that the Commons Codec result has to be recoded
* to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
*
* This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
* allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
* as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
* whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
* is quite low it probably does.<br><br>
*
* The encoder produces the same output as the Sun one except that the Sun's encoder appends
* a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
* length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
* Commons codec seem to always att a trailing line separator.<br><br>
*
* <b>Note!</b>
* The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
* thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
* format types. The methods not used can simply be commented out.<br><br>
*
* There is also a "fast" version of all decode methods that works the same way as the normal ones, but
* har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
* the input is known and it hasn't bee tampered with.<br><br>
*
* If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
*
* Licence (BSD):
* ==============
*
* Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* Neither the name of the MiG InfoCom AB nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* @version 2.2
* @author Mikael Grev
* Date: 2004-aug-02
* Time: 11:31:11
*/
public class Base64
{
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
// ****************************************************************************************
// * char[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static char[] encodeToChar(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(char[] sArr)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i]] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;)
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++]];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * byte[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i] & 0xff] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;)
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++] & 0xff];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * String version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static String encodeToString(byte[] sArr, boolean lineSep)
{
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
/** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
* and without line separators.<br>
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
* @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(String str)
{
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
// Count '=' at end
int pad = 0;
for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
if (str.charAt(i) == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[str.charAt(s++)];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String s)
{
// Check special case
int sLen = s.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[s.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
}

+ 47
- 0
src/org/r3pek/droiduptime/ConfigValues.java View File

@@ -0,0 +1,47 @@
package org.r3pek.droiduptime;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.format.DateUtils;
public class ConfigValues {
private SharedPreferences settings;
private Context ctx;
public ConfigValues(Context ctx) {
this.ctx = ctx;
settings = PreferenceManager.getDefaultSharedPreferences(ctx);
}
public String getUsername() {
return settings.getString("username", "");
}
public String getPassword() {
return settings.getString("password", "");
}
public int getUpdateInterval() {
return Integer.parseInt(settings.getString("pref_gen_update_int", "3600"));
}
public String getHostname() {
return settings.getString("pref_gen_hostname", "");
}
public String getLastUpdate() {
long lastUpdate = settings.getLong("lastUpdate", Long.MAX_VALUE);
if (lastUpdate == Long.MAX_VALUE)
return ctx.getString(R.string.notyetupdated).toString();
else
return DateUtils.getRelativeTimeSpanString(lastUpdate).toString();
}
public void setLastUpdate(Long time) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong("lastUpdate", time);
editor.commit();
}
}

+ 160
- 0
src/org/r3pek/droiduptime/DroidUptimeService.java View File

@@ -0,0 +1,160 @@
package org.r3pek.droiduptime;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.SystemClock;
public class DroidUptimeService extends Service {
private Timer timer;
private ConfigValues cv;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
cv = new ConfigValues(getApplicationContext());
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
sendUptime();
}
}, 60000, cv.getUpdateInterval() * 1000);
}
@Override
public void onDestroy() {
super.onDestroy();
if (timer != null) timer.cancel();
}
@SuppressWarnings("static-access")
private String getMACAddrMD5() {
WifiManager manager = (WifiManager)getApplicationContext().getSystemService(getApplicationContext().WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
try {
return MD5.calculateMD5(info.getMacAddress().toLowerCase().replaceAll(":", ""));
} catch (Exception e) { }
return "";
}
private String getFormattedKernelVersion() {
String procVersionStr;
try {
BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 256);
try {
procVersionStr = reader.readLine();
} finally {
reader.close();
}
final String PROC_VERSION_REGEX = "\\w+\\s+" + /* ignore: Linux */
"\\w+\\s+" + /* ignore: version */
"([^\\s]+)\\s+" + /* group 1: 2.6.22-omap1 */
"\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+" + /* group 2: (xxxxxx@xxxxx.constant) */
"\\([^)]+\\)\\s+" + /* ignore: (gcc ..) */
"([^\\s]+)\\s+" + /* group 3: #26 */
"(?:PREEMPT\\s+)?" + /* ignore: PREEMPT (optional) */
"(.+)"; /* group 4: date */
Pattern p = Pattern.compile(PROC_VERSION_REGEX);
Matcher m = p.matcher(procVersionStr);
if (!m.matches())
return "Unavailable";
else
return m.group(1);
} catch (IOException e) {
return "Unavailable";
}
}
private String getCPUABI() {
String procStr;
try {
BufferedReader reader = new BufferedReader(new FileReader("/proc/cpuinfo"), 256);
try {
procStr = reader.readLine();
} finally {
reader.close();
}
String[] cpu = procStr.replace("(", "").replace(")", "").split(" ");
return cpu[1] + "-" + cpu[5];
} catch (Exception e) {
return "";
}
}
@SuppressWarnings("static-access")
public void sendUptime() {
if (cv.getUsername().equals("") || cv.getPassword().equals(""))
return;
ConnectivityManager conMngr = (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
boolean isConnected = false || conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
isConnected |= conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
if (!isConnected) return;
long uptime = SystemClock.elapsedRealtime() / 1000;
String agent = "DroidUptime-v1.3";
String cnb = "1";
String mac = getMACAddrMD5();
String hostname = cv.getHostname();
String machine = hostname.equals("") ? android.os.Build.MODEL : hostname + " (" + android.os.Build.MODEL + ")";
String os = "Linux+" + getFormattedKernelVersion() + "+(" + getCPUABI() + ")";
String distrib = "Android";
String distribContent = "SDK " + android.os.Build.VERSION.RELEASE;
distribContent = Base64.encodeToString(distribContent.getBytes(), false);
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://update.uptimeprj.com/update.php?username=" + cv.getUsername());
post.addHeader("User-Agent", agent);
List <NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("username", cv.getUsername()));
data.add(new BasicNameValuePair("pass", cv.getPassword()));
data.add(new BasicNameValuePair("cnb", cnb));
data.add(new BasicNameValuePair("mac", mac));
data.add(new BasicNameValuePair("machine", machine));
data.add(new BasicNameValuePair("os", os));
data.add(new BasicNameValuePair("uptime", String.valueOf(uptime)));
data.add(new BasicNameValuePair("distrib", distrib));
data.add(new BasicNameValuePair("distribcontent", distribContent));
post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
httpclient.execute(post);
cv.setLastUpdate(System.currentTimeMillis());
} catch (Exception e) { e.printStackTrace(); }
}
}

+ 24
- 0
src/org/r3pek/droiduptime/DroidUptimeServiceManager.java View File

@@ -0,0 +1,24 @@
package org.r3pek.droiduptime;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class DroidUptimeServiceManager extends BroadcastReceiver {
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
ComponentName comp = new ComponentName(arg0.getPackageName(), DroidUptimeService.class.getName());
ComponentName service = arg0.startService(new Intent().setComponent(comp));
if (null == service){
// something really wrong here
Log.e(getClass().getName(), "Could not start service " + comp.toString());
}
} else {
Log.e(getClass().getName(), "Received unexpected intent " + arg1.toString());
}
}
}

+ 33
- 0
src/org/r3pek/droiduptime/MD5.java View File

@@ -0,0 +1,33 @@
package org.r3pek.droiduptime;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String calculateMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}

+ 184
- 0
src/org/r3pek/droiduptime/Main.java View File

@@ -0,0 +1,184 @@
package org.r3pek.droiduptime;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Main extends Activity {
private static final int MENU_ABOUT = 0;
private static final int MENU_SETUP = 1;
private static final int DIALOG_ABOUT = 0;
private Button btnStartStopService;
private TextView tvStatus;
private TextView tvUptime;
private TextView tvLastUpdate;
private Thread uptimeThread;
private ConfigValues cv;
private volatile boolean stopThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*AdManager.setTestDevices( new String[] {
AdManager.TEST_EMULATOR, // Android emulator
"7A352EFBD63EAC6DF4C5F8DFBC661C00", // My Nexus1
} );*/
cv = new ConfigValues(getApplicationContext());
btnStartStopService = (Button)findViewById(R.id.btnStartStopService);
tvStatus = (TextView)findViewById(R.id.tvStatus);
tvUptime = (TextView)findViewById(R.id.tvUptime);
tvLastUpdate = (TextView)findViewById(R.id.tvLastUpdate);
btnStartStopService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(getApplicationContext(), DroidUptimeService.class);
if (isServiceRunning()) {
stopService(service);
} else {
startService(service);
}
updateStatus();
}
});
}
private void startThread() {
stopThread = false;
uptimeThread = new Thread(new Runnable() {
@Override
public void run() {
while (!stopThread) {
long secondsRunning = SystemClock.elapsedRealtime() / 1000;
final int months = (int)(secondsRunning / 2592000);
final int days = (int)((secondsRunning - (months * 2592000)) / 86400);
final int hours = (int)((secondsRunning - (months * 2592000) - (days * 86400)) / 3600);
final int minutes = (int)((secondsRunning - (months * 2592000) - (days * 86400) - (hours * 3600)) / 60);
final int seconds = (int)(secondsRunning % 60);
runOnUiThread(new Runnable() {
public void run() {
tvUptime.setText(String.valueOf(months) + " " + getString(R.string.months) + ", " +
String.valueOf(days) + " " + getString(R.string.days) + ", " +
String.valueOf(hours) + " " + getString(R.string.hours) + ", " +
String.valueOf(minutes) + " " + getString(R.string.minutes) + " " +
String.valueOf(seconds) + " " + getString(R.string.seconds));
if (cv.getUsername().equals("") || cv.getPassword().equals(""))
tvLastUpdate.setText(R.string.no_user_pass);
else
tvLastUpdate.setText(cv.getLastUpdate());
updateStatus();
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) { return; }
}
}
});
uptimeThread.start();
}
@Override
public void onPause() {
super.onPause();
stopThread = true;
uptimeThread = null;
}
@Override
public void onResume() {
super.onResume();
if (uptimeThread == null)
startThread();
updateStatus();
}
private boolean isServiceRunning() {
ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
if (serviceList.size() <= 0) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName serviceName = serviceInfo.service;
if(serviceName.getClassName().equals(DroidUptimeService.class.getName())) {
return true;
}
}
return false;
}
private void updateStatus() {
if (isServiceRunning()) {
tvStatus.setText(R.string.status_running);
btnStartStopService.setText(R.string.operation_stop);
} else {
tvStatus.setText(R.string.status_stopped);
btnStartStopService.setText(R.string.operation_start);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ABOUT, 0, R.string.menu_about).setIcon(android.R.drawable.ic_menu_info_details);;
menu.add(0, MENU_SETUP, 0, R.string.menu_setup).setIcon(android.R.drawable.ic_menu_preferences);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ABOUT:
showDialog(DIALOG_ABOUT);
return true;
case MENU_SETUP:
Intent i = new Intent(getApplicationContext(), MyPreferences.class);
startActivity(i);
return true;
}
return false;
}
public Dialog onCreateDialog(int id) {
Dialog d;
switch (id) {
case DIALOG_ABOUT: {
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.about, (ViewGroup)findViewById(R.id.aboutRoot));
ImageView image = (ImageView)layout.findViewById(R.id.ImageView01);
image.setImageResource(R.drawable.icon);
Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
d = builder.create();
break;
}
default: d = null;
}
return d;
}
}

+ 13
- 0
src/org/r3pek/droiduptime/MyPreferences.java View File

@@ -0,0 +1,13 @@
package org.r3pek.droiduptime;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class MyPreferences extends PreferenceActivity {

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.preferences);
}
}

Loading…
Cancel
Save