[Guide] PHP Development on Android [25 May 2015] - General Topics

Thread link
[Guide] PHP Development on Android
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
WHAT?
Yes, you can develop with PHP on your Android device, no I am not mad (yet) - not guaranteed for lifetime. This guide is just to help you starting and hopefully kicks off some discussions about this (currently) not very common opportunity.
WHY the heck...?
Well, by now it's just playing with our devices, sure. But let's face it and let's see the potential of an Android device in the future, maybe in only a few years. Do I have to boot my computer or notebook or is it more likely I just wake my smartphone or tablet and give it a power source by placing it in the stand? Either way, it also makes fun playing around by now and using a maybe older device as a low power consuming web app server.
But PHP is ridiculous, scripting for kids, security flaws, inconsistencies, ugly syntax...
PHP is one of the most important scripting languages in the web. It's not perfect, sure, but you can create really big projects like Wordpress and vBulletin and therefore also our beloved XDA. However, this is a thread about how to start PHP developing on an Android device, not about how great or how bad this programming language is.
You have a question? Post it in the thread.
You have improvements? Post it in the thread.
You know better apps? Post it in the thread.
You don't like PHP? Well, move along...
My test set up
Hardware
Android device (Samsung Galaxy S3 LTE GT-I9305, running Android 5.0.2)
Chromecast
FHD TV
USB OTG cable
USB keyboard
Software/Apps
code editor
web server with PHP support
I develop and apply the programs locally, means, code editor and server are on the same device. Uploading or managing files remotely is not not required in this case.
Optional and recommended accessories and apps
Hardware
Bluetooth input devices, so you can charge your device
USB cable to charge your device, you'll need it
alternatively use wireless charging if your device supports it
Software/Apps
DynDNS client
port forwarder (needs root to forward to standard port 80)
SFTP/FTPS server/client
SSH server/client
server monitor
The apps will raise the battery consumption, so for longer development sessions, use Bluetooth keyboards and mice or a BT keyboard with an integrated touchpad. Charge your device.
DynDNS client makes your device available to the internet using a simple subdomain name instead of the ip address. The port forwarder can redirect incoming HTTP requests to port 80 for example. To upload and manage your files from your Android device to a web server from your web hoster, you can use secured FTP (SFTP/FTPS) and SSH clients or use servers, if you upload from an Android to an Android device.

Code editors
To write code, you'll need code editors and some of them are quite good for doing that. Try some of these following, if you don't have any yet.
AIDE Web - Html,Css,JavaScript - paid: IAP
Updated: December 11, 2014
Current Version: 1.0.3beta
AWD - PHP/HTML/CSS/JS IDE - paid: IAP
Updated: April 30, 2015
Current Version: 0.41
XDA application thread by @divers
DroidEdit (free code editor) - paid: DroidEdit Pro (code editor))
Updated: March 03, 2015
Current Version: 1.23.0
Quoda Code Editor - paid: IAP
Updated: August 14, 2014
Current Version: 1.0.1.2
Turbo Editor ( Text Editor ) - paid: IAP, Turbo Editor PRO (Text Editor)
Updated: May 15, 2015
Current Version: 2.1
XDA application thread by @Vlad Mihalachi
Web servers with PHP support
Some web servers with integrated PHP interpreter are listed below. A lot of those on Google Play have a free trial period, so try before you buy.
Down below you find three free web servers with PHP interpreter. I also checked which server software they're running and it's version, as well as the version of the PHP interpreter.
AndroPHP
Updated: February 8, 2013
Current Version: 1.2.0
Web server: Lighttpd 1.4.29
PHP version: 5.4.8
View the complete output of phpinfo() as PDF (196 kB)
Palapa Web Server
Updated: August 26, 2014
Current Version: 2.1.1
Web server: Lighttpd 1.4.32
PHP version: 5.5.15
View the complete output of phpinfo() as PDF (291 kB)
Server for PHP
Updated: May 24, 2015
Current Version: 1.7.0
Web server: PHP 5.6.9 Development Server
PHP version: 5.6.9
View the complete output of phpinfo() as PDF (361 KB)
This one is basically a server collection, tons of servers for all your needs. Slightly outdated, no update for quite a long time, therefore an old PHP version. Hopefully the app gets new and updated servers. Trial version available.
Servers Ultimate (7 days trial) - paid: Servers Ultimate Pro
Updated: June 16, 2014
Current Version: 6.3.10
Web server: Lighttpd
PHP version: 5.4.8
View the complete output of phpinfo() as PDF (197 kB)
XDA application thread by @Themuzz
Web server monitor
To monitor your mobile web server, I recommend to set up a server monitor app, like Monyt - Server Monitor. The app itself is a client, pulling information from a script you have to place on your server. Just for the records, it's a PHP script.
Monyt - Server Monitor
Updated: March 15, 2013
Current Version: 1.1.4
XDA application thread by @evilsocket
Install Monyt - Server Monitor from Google Play store (on any Android device, this is basically only the client)
Paste the PHP code into a *.php file (link in the Google Play description) (on the server)
Configure the app, at least enter the URL to the PHP script
The monitor app can also be installed on your mobile server.
Some screenshots made on a Sony Xperia Z3
Current link and content of the PHP script: http://www.monyt.net/monyt-server-script.txt
PHP:
<?php
error_reporting(0);
define( "MONYT_SCRIPT_VERSION", "1.0.1" );
if( isset($_GET['version'] ) )
{
die( MONYT_SCRIPT_VERSION );
}
else if( isset($_GET['check']) )
{
$aCheck = array
(
'monyt' => MONYT_SCRIPT_VERSION,
'distro' => '',
'kernel' => '',
'cpu' => '',
'cores' => ''
);
$sDistroName = '';
$sDistroVer = '';
foreach (glob("/etc/*_version") as $filename)
{
list( $sDistroName, $dummy ) = explode( '_', basename($filename) );
$sDistroName = ucfirst($sDistroName);
$sDistroVer = trim( file_get_contents($filename) );
$aCheck['distro'] = "$sDistroName $sDistroVer";
break;
}
if( !$aCheck['distro'] )
{
if( file_exists( '/etc/issue' ) )
{
$lines = file('/etc/issue');
$aCheck['distro'] = trim( $lines[0] );
}
else
{
$output = NULL;
exec( "uname -om", $output );
$aCheck['distro'] = trim( implode( ' ', $output ) );
}
}
$cpu = file( '/proc/cpuinfo' );
$vendor = NULL;
$model = NULL;
$cores = 0;
foreach( $cpu as $line )
{
if( preg_match( '/^vendor_id\s*:\s*(.+)$/i', $line, $m ) )
{
$vendor = $m[1];
}
else if( preg_match( '/^model\s+name\s*:\s*(.+)$/i', $line, $m ) )
{
$model = $m[1];
}
else if( preg_match( '/^processor\s*:\s*\d+$/i', $line ) )
{
$cores++;
}
}
$aCheck['cpu'] = "$vendor, $model";
$aCheck['cores'] = $cores;
$aCheck['kernel'] = trim(file_get_contents("/proc/version"));
die( json_encode($aCheck) );
}
$aStats = array( 'monyt' => MONYT_SCRIPT_VERSION );
$aStats['uptime'] = trim( file_get_contents("/proc/uptime") );
$load = file_get_contents("/proc/loadavg");
$load = explode( ' ', $load );
$aStats['load'] = $load[0].', '.$load[1].', '.$load[2];
$memory = file( '/proc/meminfo' );
foreach( $memory as $line )
{
$line = trim($line);
if( preg_match( '/^memtotal[^\d]+(\d+)[^\d]+$/i', $line, $m ) )
{
$aStats['total_memory'] = $m[1];
}
else if( preg_match( '/^memfree[^\d]+(\d+)[^\d]+$/i', $line, $m ) )
{
$aStats['free_memory'] = $m[1];
}
}
$aStats['hd'] = array();
foreach( file('/proc/mounts') as $mount )
{
$mount = trim($mount);
if( $mount && $mount[0] == '/' )
{
$parts = explode( ' ', $mount );
if( $parts[0] != $parts[1] )
{
$device = $parts[0];
$folder = $parts[1];
$total = disk_total_space($folder) / 1024;
$free = disk_free_space($folder) / 1024;
if( $total > 0 )
{
$used = $total - $free;
$used_perc = ( $used * 100.0 ) / $total;
$aStats['hd'][] = array
(
'dev' => $device,
'total' => $total,
'used' => $used,
'free' => $free,
'used_perc' => $used_perc,
'mount' => $folder
);
}
}
}
}
$ifname = NULL;
if( file_exists('/etc/network/interfaces') )
{
foreach( file('/etc/network/interfaces') as $line )
{
$line = trim($line);
if( preg_match( '/^iface\s+([^\s]+)\s+inet\s+.+$/', $line, $m ) && $m[1] != 'lo' )
{
$ifname = $m[1];
break;
}
}
}
else
{
foreach( glob('/sys/class/net/*') as $filename )
{
if( $filename != '/sys/class/net/lo' && file_exists( "$filename/statistics/rx_bytes" ) && trim( file_get_contents("$filename/statistics/rx_bytes") ) != '0' )
{
$parts = explode( '/', $filename );
$ifname = array_pop( $parts );
}
}
}
if( $ifname != NULL )
{
$aStats['net_rx'] = trim( file_get_contents("/sys/class/net/$ifname/statistics/rx_bytes") );
$aStats['net_tx'] = trim( file_get_contents("/sys/class/net/$ifname/statistics/tx_bytes") );
}
else
{
$aStats['net_rx'] =
$aStats['net_tx'] = 0;
}
die( json_encode( $aStats ) );
?>

Reserved

Bump... 1 month online and 181 views but no reaction
Somewhere a PHP developer... or a somehow interested one in any kind of coding on Android... or at least someone who heard about PHP or Android?

Hellow, i have been developing php on my android since 2013
The app that I used was AndroPHP but now is off the playStore
Also i have found an error on the Palapa Web Server on the moto g since it can't install the services and is useless to my client since he is buying moto g as the main device, I have a nexus 6 and an Intel tablet and i dont have this problem
I think i have the apk of AndroPhp somewhere in case someone need it

atondo27 said:
Hellow, i have been developing php on my android since 2013
The app that I used was AndroPHP but now is off the playStore
Also i have found an error on the Palapa Web Server on the moto g since it can't install the services and is useless to my client since he is buying moto g as the main device, I have a nexus 6 and an Intel tablet and i dont have this problem
I think i have the apk of AndroPhp somewhere in case someone need it
Click to expand...
Click to collapse
Thanks for your post. Developing PHP on Android since 2013 is quite a long time, but obviously it was possible. Do you still develop on Android and what's your setup like keyboard, mouse, monitor etc.?
I think I'll just remove the Palapa Web Server, which was removed recently from the Play Store. Can you suggest other code editors or development environments/servers?

atondo27 said:
Hellow, i have been developing php on my android since 2013
The app that I used was AndroPHP but now is off the playStore
Also i have found an error on the Palapa Web Server on the moto g since it can't install the services and is useless to my client since he is buying moto g as the main device, I have a nexus 6 and an Intel tablet and i dont have this problem
I think i have the apk of AndroPhp somewhere in case someone need it
Click to expand...
Click to collapse
Hi, also noticed that the amazing small and free Androphph is no longer on the playstore. Any ideas as to why it was removed? To be honest that app was rock solid in php/mysql.

ProjectER said:
Hi, also noticed that the amazing small and free Androphph is no longer on the playstore. Any ideas as to why it was removed? To be honest that app was rock solid in php/mysql.
Click to expand...
Click to collapse
I have been strugling with Androphp and Lolipop on the Moto G. Its been like 1 year since it was removed.
you can download the apk from here:
***.apk4fun.com/apps/com.ayansoft.androphp/
www
I'm using that version on some deployments

Related

[APP] Shark for Root + SharkReader

There were AndroShark, tool for capturing traffic on Android. But there were no newer releases and it seems that original developer dropped project. I liked this tool and used it a lot. But it was set to expire... So there was no simple capture tools available... http://forum.xda-developers.com/showthread.php?t=675206 is home of AndroShark.
So I made Shark for Root, alternative for AndroShark. Some people asked for possibility to see packets on phone, and for that purpose SharkReader has created (first, "quick and dirty" release).
Shark for Root
With tcpdump http://swapper.n3o.lv/lv.n3o.shark_1.0.2.apk
Native http://swapper.n3o.lv/lv.n3o.sharknative_1.0.2.apk
SharkReader - unstable...
(note - run Shark Updater to get traffic analysator)
http://swapper.n3o.lv/lv.n3o.sharkreader_0.1.6.apk
Older versions http://swapper.n3o.lv/
EPIC
Thank you!
If you press stop, it doesn't truly stop. tcpdump seems like it is still going in the background. The file will continue getting larger and larger even though it has been told to stop capturing.
Running CyanogenMod 6 RC1.
Thank you.
Far as I can tell it's working good, Thanks for the reader, helps a lot, I can see this program becoming a portable wireshark app for android, keep up the great work and thank you.
Awesome start!! Thanks!
Sent from my Nexus One using XDA App
does this program work with rooted x10? i clcik on start and all i see is "not found".. my parameters are empty is this also correct ?
thanks
cool app! thanks!
duffy1807 said:
does this program work with rooted x10? i clcik on start and all i see is "not found".. my parameters are empty is this also correct ?
thanks
Click to expand...
Click to collapse
Default parameters are -vv -s 0
Can You send me more information about Your error?
Could someone tell about using different parameters or point me to some website where i could study these?(now i got the defaults)
And when i open Shark reader i see many "RAW Packet" but i cant get any information from them, just "Packet #number".
.pcap files are fine when i open them with Wireshark.
At the bottom i see this: -NULL , what else i can use here and how it effects?
Interesting app, keep up the good work!
A changelog would be nice.
I also can not run Shark on my X10. I get the error 'reloc_library [1215]: cannot locate _aeabi_fdiv CANNOT LINK EXECUTABLE
Sent from my X10a using XDA App
acips said:
Could someone tell about using different parameters or point me to some website where i could study these?(now i got the defaults)
And when i open Shark reader i see many "RAW Packet" but i cant get any information from them, just "Packet #number".
.pcap files are fine when i open them with Wireshark.
At the bottom i see this: -NULL , what else i can use here and how it effects?
Interesting app, keep up the good work!
Click to expand...
Click to collapse
Hello!
For Shark for Root parameters look at some examples/manuals about tcpdump. F.e. http://www.cs.ucr.edu/~marios/ethereal-tcpdump.pdf
Shark reader marks packets as RAW if it does not recognize it (currently it means it's not tcp/udp packet).
For filters you can use any tag and any tag with - sign. Tags are those in first column. Traffic is tagged by content (signature) and port. Signatures and ports you may update with Shark Updater (included in Shark Reader), but I have too little time to manage all those resources. I'll make this system public for tags submission/port submission, so interested users will be able to add necessary tags.
So, if you want to see only non zero bytes packets with http content, you may use this setting:
Code:
[ ] all [o] none | http -NULL |
Filters are processed in order. So http shows all http packets and -NULL hides those with nulls. First option works as global filter (show all or show none).
Warning! Not all traffic is tagged, so if you miss something, it could mean some tags are incorrectly assigned or skipped.
Hope it helps.
mcampbellsmith said:
I also can not run Shark on my X10. I get the error 'reloc_library [1215]: cannot locate _aeabi_fdiv CANNOT LINK EXECUTABLE
Sent from my X10a using XDA App
Click to expand...
Click to collapse
Which OS version your X10a have? I saw that there are some problems with reloc_library in Android 1.5.
It's Android 1.6 only on the X10
Sent from my X10a using XDA App
i made an spanish thread on my android site, lets see how it works on milestone
thanks!!!!
Can some please explain in lamon terms what this does?
hy there =) can you make a capture filter to msn conversations ? it would be nice =)
I use an app similar called 3G Watchdog (it's free).
Let's you know how much data you've used with a widget too!
slow4g63 said:
I use an app similar called 3G Watchdog (it's free).
Let's you know how much data you've used with a widget too!
Click to expand...
Click to collapse
LOL this is nothing like that my friend.. nothing at all
ex87,
Awesome work bro, life got too busy for me to work more on AndroShark, I really didn't drop it on purpose. But with a busy life, and me still really new at java, it was just too much. I am really glad you picked up the idea and ran with it.
Do you have any plans to opensource it at all (no worries if you dont)? I would like to be a contributor if you do decide to open source it.
I really doubt this is of any use. It was the second java app I ever worked on, and was really just a front end. Below is androshark source code. Like I said, this was my second attempt at writing an app, so please don't laugh If I were to do it today, I would completely change how it worked. /res/raw/sharktap was just tcpdump.
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* ToDo:
* Check for root
* Check for first run
* Install Binaries on first run
* Check for sdcard mount
* Display file stats
* Name pcap based on file name
* Insert License
* kill sharktap on die
*
* @author jcase
*
*/
public class androshark extends Activity implements /*RadioGroup.OnCheckedChangeListener,*/ Button.OnClickListener {
Button btnStart, btnStop;
RadioButton radAll, rad3g, radWifi; //http://java.dzone.com/articles/google-android-tutorial?page=0,4
RadioGroup grpRadio;
TextView txtStatus, txtFilename, txtFilesize;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStart = (Button)this.findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
btnStop = (Button)this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
long epoch = System.currentTimeMillis()/1000;
boolean exists = (new File("/data/data/net.andirc.androshark/files/sharktap")).exists();
if (exists) {
} else {
Process myproc = null;
try
{
try{
String strDirectoy ="/data/data/net.andirc.androshark/files";
new File(strDirectoy).mkdir();
}
finally {}
InputStream ins = getResources().openRawResource(R.raw.sharktap);
int size = ins.available();
byte[] buffer = new byte[size];
ins.read(buffer);
ins.close();
FileOutputStream fos = new FileOutputStream("/data/data/net.andirc.androshark/files/sharktap");
fos.write(buffer);
fos.close();
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
}
boolean exists2 = (new File("/sdcard/androshark/")).exists();
if (exists2) {
} else {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
Process myproc = null;
try
{
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c","chmod 755 /data/data/net.andirc.androshark/files/sharktap && mkdir /sdcard/androshark/"});
new AlertDialog.Builder(this)
.setMessage("This is a beta trial version of androshark and will expire on May 15th 2010. This app can potentially consume a lot of sdcard space, depending on how long you allow it to sniff traffic and how much bandwidth you are using.")
.setPositiveButton("OK", null)
.show();
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
} else {
new AlertDialog.Builder(this)
.setMessage("Error sd01: sdCard not found!")
.setPositiveButton("OK", null)
.show();
}
}
if (epoch >= 1273990849) { // May 15th 2010 1273990849
System.exit(0);
}
}
public void onClick(View v) {
Process myproc = null;
try
{
if (v == btnStart) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c", "kill $(ps | grep sharktap | tr -s ' ' | cut -d ' ' -f2) && /data/data/net.andirc.androshark/files/sharktap -vv -s 0 -w /sdcard/androshark/dump.pcap"});
TextView txtStatus =
(TextView) this.findViewById(R.id.txtStatus);
txtStatus.setText("Status: Running");
TextView txtFilename =
(TextView) this.findViewById(R.id.txtFilename);
txtFilename.setText("Filename: /sdcard/androshark/dump.pcap");
/* int running = 1;
do {
File file = new File("/sdcard/androshark/dump.pcap");
long length = file.length();
TextView txtFilesize =
(TextView) this.findViewById(R.id.txtFilesize);
txtFilesize.setText("File Size: " + length/1024 + "KB");
} while (running <= 1); */
} else {
new AlertDialog.Builder(this)
.setMessage("Error sd02: sdCard not found!")
.setPositiveButton("OK", null)
.show();
}
} else if (v == btnStop) {
myproc = Runtime.getRuntime().exec(new String[] {"su", "-c", "kill $(ps | grep sharktap | tr -s ' ' | cut -d ' ' -f2)"});
myproc.waitFor();
File file = new File("/sdcard/androshark/dump.pcap");
long length = file.length();
TextView txtStatus =
(TextView) this.findViewById(R.id.txtStatus);
txtStatus.setText("Status: Stopped");
TextView txtFilesize =
(TextView) this.findViewById(R.id.txtFilesize);
txtFilesize.setText("File Size: " + length/1024 + "KB");
}
}
catch (Exception ex)
{
Log.e("yourTag", "Oops something happened: " + ex.getMessage(), ex);
}
finally {}
}
}
racemepls said:
Can some please explain in lamon terms what this does?
Click to expand...
Click to collapse
shdwknt said:
LOL this is nothing like that my friend.. nothing at all
Click to expand...
Click to collapse
Apparently you know, and still haven't helped those of us who have no idea what this app is for!

[APP] Zune software remote control

Instructions + download: http://forum.xda-developers.com/showpost.php?p=17254652&postcount=7
I have finally found a way to control the Zune software running on Windows. The Zune API is horrible so there are few(if any) programs that interface with the software externally. Today I came across the SendMessage method. The idea is your Android device is a big remote control for the Zune software. If you already have a media remote then this application isn't needed. I only have a remote on my laptop, not desktop so that's why I'm bothering to write it. I thought I would share it on XDA for free.
http://pastebin.com/C85isGsW - that was my test program. When I opened it my music paused(yay!).
Anyways this will be a 2-part system. The Windows app will run in the background(either as a service or in the system tray) and listen on some random TCP port for a connection. It will be relatively small, using less than 50MB RAM. This one uses 27MB right now(yes, C# is bloated).
The Android app will simply connect over the wifis or even over the internet(just remember to forward ports) and after a quick handshake it will be able to send and receive data from the service/app in tray. First I'll start with simple play/pause buttons and a volume slider and eventually I'll add all the interfaces listed here: http://msdn.microsoft.com/en-us/library/ms646275(v=vs.85).aspx
Step 1: install service or open the Windows program
Step 2: type computer IP in android app
Step 3: press play/pause or control volume etc. It will save the IP so you don't have to keep typing it in. In fact I will have a dropdown list so you can select different computers(HTPC, basement computer etc.)
I just started writing the program so it will by done by the end of the weekend. Figured I would create the thread since I know it will work.
inb4 zune sucks
Interested in seeing this.
Sent from my Transformer TF101 using XDA Premium App
yes dude yes!!! imso amped for this! thanks so much.
OK I got the windows side app 95% done... started the Android version and well.. I'm a noob. Looks like honeycomb makes you interface with TCP in a separate thread...
Windows server code:
Code:
hile (stop != 1)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Console.WriteLine("Received: {0}", data);
if (Convert.ToString(data).CompareTo("PP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PLAY_PAUSE);
if (Convert.ToString(data).CompareTo("UP") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_UP);
if (Convert.ToString(data).CompareTo("DN") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_VOLUME_DOWN);
if (Convert.ToString(data).CompareTo("PR") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_PREVIOUSTRACK);
if (Convert.ToString(data).CompareTo("NE") == 0) SendMessageW(hwnd, WM_APPCOMMAND, hwnd, (IntPtr)APPCOMMAND_MEDIA_NEXTTRACK);
// Process the data sent by the client.
//device.AudioEndpointVolume.MasterVolumeLevelScalar = (Convert.ToInt64(data) / 100.0f);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes("Successfully set to " + data);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
What needs to happen to connect to the server(client code)
Code:
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
MessageBox.Show("ArgumentNullException: " + e.ToString());
}
catch (SocketException e)
{
MessageBox.Show("SocketException: " + e.ToString());
}
}
So I would call Connect("192.168.1.40", "PP"); to pause/play the server(desktop running Zune)
Code:
package com.pwn.control;
import android.app.Activity;
import java.io.*;
import java.net.*;
import android.widget.*;
import android.os.Bundle;
import android.os.StrictMode;
public class ControlActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText("HELLO WORLD");
setContentView(tv);
run();
}
TextView tv;
public void run()
{
new Thread(new Runnable() { public void run() {
Socket socket;
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.1.40");
socket = new Socket("192.168.1.40", 13000);
//socket.connect();
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes("PP");
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//out.println("PP");
socket.close();
}
catch (Exception e)
{
tv.setText(e.toString());
//setContentView(R.layout.main);
}
}
} ).start();
}
}
Unfortunately the above code doesn't work. Kinda stuck lol... maybe someone knows more about writing android apps than I do.
http://www.youtube.com/watch?v=PMjNrd1d4FM
Got it working with an ASP site...
now the annoying part... I tried setting it up with a default IIS instance and it doesn't have permissions to use the user32.dll!!! I tried forced impersonation and tons of different tricks but for some reason it isn't getting as high permissions as the ASP.NET debugging server.
So I need to either fix the android app so it will communicate with the service, or I need to find a way to get the IIS instance enough permissions to interact with the desktop. I did set the IIS Admin service to "interact with desktop" but nothing happened.
I also tried setting up Apache 2.2 with mod_asp installed but it has the same result... blocked from interacting.
Ok I got it working but it's really really makeshift right now...
ASP website --> loopback on port 13000 --> C# app(that will actually interface with the Zune software)
I couldn't make the API call from the C# code in the ASP site because IIS doesn't have enough permissions. So since my only drawback before was that I couldn't communicate between .NET TcpListener and Java, I can just use the ASP site to make the TcpClient connection.
The good thing is you can access this interface from anything with a web browser. Just make http://computer-ip:port/ZuneControl a favorite on any device and you can control Zune from it.
http://www.youtube.com/watch?v=haVLCOY0l6U
If you're really eager to try the alpha build with IIS that's fine...
Just set up IIS like I do in the video and add port 13000 to your inbound and outbound firewall rule. I'll work on the UI when I get some time next weekend.
Here is the code for the C# app. http://pastebin.com/08kCjKQW
The web code is in the RAR file. I just copied and pasted out of that pastebin with some extra buttons.
http://tunerspotter.com/\dropbox\misc\ZuneControl.rar
In that ZuneControl folder, ZuneControl.exe is the app. Click start, then minimize it after you set up IIS. It will work for Apache installations also. I have Apache on port 82. http://sourceforge.net/projects/mod-aspdotnet/
Instruction video: http://www.youtube.com/watch?v=ClCQhmQxC7Q
Well i've been using the web interface for a few days and it kicks ass. Does exactly what i want. I can be in bed and change songs/volume from another tab in Opera.
Next weekend Ill see if i can get the program to listen on port 81 as a web service so instead of setting up IIS or apache all you have to do is open the app and click start(then minimize it)
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
hey are you still working on this? I would really love something like this!
well i gave up on the app and just turned it into a ASP site + windows application. so yeah i've been using it for a few months. works great, i can pull up on any web capable device and adjust my music. Whether it's my zune, tablet, computer, or phone, i can adjust volume, go back/next, and pause/play from any device. i set up port forwarding with dyndns.org so it works over 3G

[Q] WP7 facebook application, posting blank status updates only

Hi ive written a simple application for windows phone 7 that posts a status update to the users wall. This is all working correctly except for the fact that when the status update is done it is always empty. I am trying to make it so that the user can enter what they would like to say in a text box, but obviously so far this isnt working and all that is being sent is an empty status update. I am connecting to the facebook api and the authentication all works correctly or the post would not be sent at all. Ive searched all over the web and havent found anyone with the same issue as of yet.
Here is the status update code that I am working on:
Code:
private void PostStatusUpdate(string status, Action<bool, Exception> callback)
{
var request = HttpWebRequest.Create("https://graph.facebook.com/me/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (var strm = request.EndGetRequestStream(reqResult))
using (var writer = new StreamWriter(strm))
{
writer.Write("access_token=" + _accessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
}
[DataContract]
public class FacebookPostResponse
{
[DataMember(Name = "id")]
public string Id
{
get;
set;
}
}
private void PostUpdate_Click(object sender, RoutedEventArgs e)
{
PostStatusUpdate(this.StatusText.Text, (success, ex) =>
{
this.Dispatcher.BeginInvoke(() =>
{
if (success && ex == null)
{
MessageBox.Show("Status updated");
NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Unable to update status");
}
});
});
}
Has anyone encountered this before / know any solution to this problem?
Any insights into this would be much appreciated
You are using the asyncronous method with no callback function
Looks like you should be using a callback function - See examples here
http://msdn.microsoft.com/en-us/lib...est.begingetrequeststream(v=vs.90).aspx#Y1760
http://msdn.microsoft.com/en-us/lib...brequest.begingetrequeststream(v=vs.100).aspx
Also, did the same code work at one point?
It could be as simple as not closing your connections. I ran into this in the Weather City Editor that I wrote for Windows Mobile.
When I added code to hit accuweathers site to look up the code, I had forgotten to close the connection. I would need to wait until the connection timed out before it would work again.
I think yours is differnt though, since it is updating blank.
But, you could just use GetRequestStream, which does not need the callback function, synce it is not asyncronous. See example code: http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx
Thanks for the reply
Thanks for the reply, the code has never worked so far it has only posted blank facebook statuses, I will see if adding an asynchronous call back makes a difference.
Thanks

Cameras from CM10.2/AOSP with SD support and geotags/timestamp in Exif

upd:The problem below affects some devices like Motorola Razr or Galaxy S3 Mini and is caused by camera driver.
Hello. Recently i've been crying all around the internet that camera doesn't include gps info in exif tags.
Nobody helped me, so i built camera from source in android studio. Used xmpCore and mp4parser.
13-08-15: Added 2 lines in PhotoModule.java:
Code:
[COLOR="silver"] exif.setTag(directionTag);
}[/COLOR]
if(mLocation != null)
exif.addGpsTags(mLocation.getLatitude(), mLocation.getLongitude());
[COLOR="Silver"] mActivity.getMediaSaveService().addImage([/COLOR]
Also changed everywhere
Code:
import android.[COLOR="Silver"][strike]support.v8.[/strike][/COLOR]renderscript<...>
And in VideoUtils.java:
Code:
[COLOR="Silver"]IsoFile out = [/COLOR](IsoFile)[COLOR="silver"]new DefaultMp4Builder().build(movie);[/COLOR]
UPD 13-08-20: user The_ERROR asked for date/time stamp in exif, so i updated the app. PhotoModule.java new changes:
Code:
79a80
> import java.util.TimeZone;
864c865
< if(mLocation != null)
---
> if(mLocation != null) {
865a867,869
> exif.addGpsDateTimeStampTag(date);
> }
> exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME, date, TimeZone.getDefault());
UPD 13-08-22: No more crashes on clicking "Show on map" menu item if google maps not installed. GalleryUtils.java:
Code:
284a285
> if(!checkActivityFound(context, mapsIntent)) throw new ActivityNotFoundException();
291c292
< context.startActivity(mapsIntent);
---
> if(checkActivityFound(context, mapsIntent)) context.startActivity(mapsIntent);
294a296,301
> private static boolean checkActivityFound(Context context, Intent intent) {
> List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
> PackageManager.MATCH_DEFAULT_ONLY);
> return list.size() > 0;
> }
>
UPD 13-08-23: Super cool things happen! I managed to compile CM10.2 camera with internal/external storage location option even before official nightly And integrated all my changes in it. Checked on CM10.2. It works.
Reopen camera after changing storage location or sliding right>left you will list photos from previous location. Though new photos go to the right one anyway.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Remove standard gallery2 using smth like RootAppDelete or ES file explorer and reboot before installing. I tried this app in CM10.1, CM10.2.
andray said:
Hello. Recently i've been crying all around the internet that camera doesn't include gps info in exif tags.
Nobody helped me, so i built camera from source in android studio. .....
Click to expand...
Click to collapse
amazing... I'm forcing similar problem, but I would like to have some kind of timestamp in EXIF data as well. Do you thing, that it would be possible to add it into your compiled version?
I'm at work now, so cannot try anything, but i see two auxiliary functions in ExifInterface.java
Code:
/**
* Creates, formats, and sets the DateTimeStamp tag for one of:
* {@link #TAG_DATE_TIME}, {@link #TAG_DATE_TIME_DIGITIZED},
* {@link #TAG_DATE_TIME_ORIGINAL}.
*
* [user=955119]@param[/user] tagId one of the DateTimeStamp tags.
* [user=955119]@param[/user] timestamp a timestamp to format.
* [user=955119]@param[/user] timezone a TimeZone object.
* [user=2056652]@return[/user] true if success, false if the tag could not be set.
*/
public boolean addDateTimeStampTag(int tagId, long timestamp, TimeZone timezone) {
if (tagId == TAG_DATE_TIME || tagId == TAG_DATE_TIME_DIGITIZED
|| tagId == TAG_DATE_TIME_ORIGINAL) {
mDateTimeStampFormat.setTimeZone(timezone);
ExifTag t = buildTag(tagId, mDateTimeStampFormat.format(timestamp));
if (t == null) {
return false;
}
setTag(t);
} else {
return false;
}
return true;
}
/**
* Creates and sets the GPS timestamp tag.
*
* [user=955119]@param[/user] timestamp a GPS timestamp.
* [user=2056652]@return[/user] true if success, false if could not be created or set.
*/
public boolean addGpsDateTimeStampTag(long timestamp) {
ExifTag t = buildTag(TAG_GPS_DATE_STAMP, mGPSDateStampFormat.format(timestamp));
if (t == null) {
return false;
}
setTag(t);
mGPSTimeStampCalendar.setTimeInMillis(timestamp);
t = buildTag(TAG_GPS_TIME_STAMP, new Rational[] {
new Rational(mGPSTimeStampCalendar.get(Calendar.HOUR_OF_DAY), 1),
new Rational(mGPSTimeStampCalendar.get(Calendar.MINUTE), 1),
new Rational(mGPSTimeStampCalendar.get(Calendar.SECOND), 1)
});
if (t == null) {
return false;
}
setTag(t);
return true;
}
and in PanoramaModule.java
Code:
exif.addGpsDateTimeStampTag(mTimeTaken);
exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME, mTimeTaken,
TimeZone.getDefault());
The_ERROR said:
amazing... I'm forcing similar problem, but I would like to have some kind of timestamp in EXIF data as well. Do you thing, that it would be possible to add it into your compiled version?
Click to expand...
Click to collapse
Ok. I did this. Here're new exif fields according to Jeffrey's Exif viewer, date/time fields are bold. If geo-location is turned off in Camera, only "Modify Date" tag will be added.
GPS Latitude Ref
GPS Latitude
GPS Longitude Ref
GPS Longitude
GPS Time Stamp
GPS Date Stamp
Modify Date
A patch of PhotoModule.java:
Code:
79a80
> import java.util.TimeZone;
864c865
< if(mLocation != null)
---
> if(mLocation != null) {
865a867,869
> exif.addGpsDateTimeStampTag(date);
> }
> exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME, date, TimeZone.getDefault());
I'll update first post now
Is there way how to chose default storage for photo? I'm not able to find it.
I think storage settings will be included in next CM10.2 nigthly http://review.cyanogenmod.org/#/c/47623/ Storage location configuration options
The bad thing - i used AOSP sources.)
By the way, i patched camera sources to not crash on clicking "Show on map" menu item if google maps not installed. GalleryUtils.java:
Code:
284a285
> if(!checkActivityFound(context, mapsIntent)) throw new ActivityNotFoundException();
291c292
< context.startActivity(mapsIntent);
---
> if(checkActivityFound(context, mapsIntent)) context.startActivity(mapsIntent);
294a296,301
> private static boolean checkActivityFound(Context context, Intent intent) {
> List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
> PackageManager.MATCH_DEFAULT_ONLY);
> return list.size() > 0;
> }
>
The_ERROR said:
Is there way how to chose default storage for photo? I'm not able to find it.
Click to expand...
Click to collapse
Woo-hoo! Now we can choose default storage! Read first post.
Thanks for this! Been looking for it
EDIT: FCs on razr i when i open camera, cm version
anerik said:
EDIT: FCs on razr i when i open camera, cm version
Click to expand...
Click to collapse
CM version WHICH? As for me, camera FCs 2-3 times after install on cm10.1/2. This version or standard one, no matter. I have razr maxx only.
andray said:
CM version WHICH? As for me, camera FCs 2-3 times after install on cm10.1/2. This version or standard one, no matter. I have razr maxx only.
Click to expand...
Click to collapse
not runnin cm, i mean the cm gallery u uploaded gives me fc when i open the camera
anerik said:
not runnin cm, i mean the cm gallery u uploaded gives me fc when i open the camera
Click to expand...
Click to collapse
ok. you can check what's going on in using Logcat Extreme. I don't know ur android version, but 4.0 is not enough. i've tried now gallery works, camera fcs
upd: AOSP version fully works on android 4.0
andray said:
ok. you can check what's going on in using Logcat Extreme. I don't know ur android version, but 4.0 is not enough. i've tried now gallery works, camera fcs
upd: AOSP version fully works on android 4.0
Click to expand...
Click to collapse
Android 4.1.2, logcat extreme doesnt really work. Is there any other way to logcat?
anerik said:
Android 4.1.2, logcat extreme doesnt really work. Is there any other way to logcat?
Click to expand...
Click to collapse
i don't know. some app from market found with "logcat" query?) or logcat command in terminal emulator. I have 4.0 and 4.2 installed.

[GUIDE] Create “deathless” Android application: Protected from removal and stop

Author: Apriorit (@andruwik777, Driver Development Team)
Some types of applications require that the end users can not be able to remove or at least stop the application. For example, all types of Parental Controls, Data Leak Prevention, and applications with similar concepts should work on devices regardless of the user’s intentions. On the other hand, when trying to search proven solutions for implementing such applications, we cannot find some comprehensive answers in the Internet. This article describes one of the possible solutions.
Intro
Though, there are individual solutions for the "Disable force stop and uninstall button on Android" tasks, but in order to activate these buttons, you simply need to perform the user’s actions in reverse order.
As for the task of creation of an unkillable application, there are opinions that it cannot be supported by the concept of Android (1, 2, 3), because the basic idea of this OS is to give the user permission to work with his device as he wishes.
However, we are going to consider one of the ways to create an application that can be stopped or removed only by the user (Admin), who installed it.
The task
Appearance of the application
Task: Create the TryStopOrUninstallMe application.
After the application start and security policy acceptance, within a 10 seconds timeout, application displays the information that it successfully works (Toast with the “Ooops! Try to kill me ” text).
If you stop the service, it will be restarted no later than in 2 seconds (by timeout).
The ForceStop and Uninstall buttons are inactive in the application menu. When you try to activate these buttons by disabling DeviceAdministrator for the application, phone is locked. At the same time the previous user password is deleted and further calls can be made only after unlocking the phone by administrator, who knows the password.
Used technologies
Programming language: Java.
Used libraries and technologies: Android SDK.
Minimum supported version of Android: 2.2
Maximum supported version of Android: 5.0.2 (the newest one for today)
ROOT-permissions requirements on the device: not required
Testing: the application was tested on Nexus 5 with Android 5.0.1.
Pending issues
In order to keep this article short and because of the triviality of the problem, we do not consider:
1. Creation of start Activity, in which the administrator would set a master password. Instead, we have simply hardcoded it (e.g., "12345");
2. Application startup at system startup.
The general principles of the mechanism
The following approaches will be used to implement this idea:
1. Disabling the application forced stop and uninstall will be implemented using Device Administration API. Although it is designed for a little bit different purposes (some of which will be shown later), we’ll use it as a "deactivator" of the ForceStop and Uninstall buttons for our application (a side effect is actually what we need):
To uninstall an existing device admin application, users need to first unregister the application as an administrator.
2. There is no standard mechanism to disable the DeviceAdmin mode unlocking for user. However, we can sign up to receive event alerts on removing our application from the list of administered ones. And in this case we can:
1. Reset the current password for device locking (one of the DeviceAdmin API purposes);
2. Lock the phone (another great DeviceAdmin API feature).
3. Our application will use the service to run in the background. For the cases when user tries to stop our service (Settings -> Application -> RunningServices) we will implement auto-start using the AlarmManager system mechanism.
4. If user stop the service and have enough time to go to the application menu until the system restarts the service, then the application (not the service) stop button will be available for him.
After application is stopped, nothing can be restarted by itself. Thus, to deprive user of this chance, we will redirect him to his desktop and lock the device. While user is returning to the target Activity, system has enough time to restart the service (during my testing, it always takes 1-2 seconds).
Graphical representation
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Implementation of the mechanism
Activation of the mechanism for self-protection against the application stop and uninstall, and the service launch (MainActivity.java)
Code:
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 0;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Initiate DevicePolicyManager.
DevicePolicyManager policyMgr = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// Set DeviceAdminDemo Receiver for active the component with different option
ComponentName componentName = new ComponentName(this, DeviceAdminDemo.class);
if (!policyMgr.isAdminActive(componentName)) {
// try to become active
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Click on Activate button to protect your application from uninstalling!");
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
startService(new Intent(this, BackgroundService.class));
}
}
Everything that is done in the main (and only one) Activity is DeviceAdmin activation and service launch. It is expected that the device administrator activates the protection by pressing Activate.
Otherwise, the user can stop or remove the application in a standard way.
The service launch and its running (BackgroundService.java)
Code:
public class BackgroundService extends Service {
private static final int FIRST_RUN_TIMEOUT_MILISEC = 5 * 1000;
private static final int SERVICE_STARTER_INTERVAL_MILISEC = 1 * 1000;
private static final int SERVICE_TASK_TIMEOUT_SEC = 10;
private final int REQUEST_CODE = 1;
private AlarmManager serviceStarterAlarmManager = null;
private MyTask asyncTask = null;
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onCreate() {
super.onCreate();
// Start of timeout-autostarter for our service (watchdog)
startServiceStarter();
// Start performing service task
serviceTask();
Toast.makeText(this, "Service Started!", Toast.LENGTH_LONG).show();
}
private void StopPerformingServiceTask() {
asyncTask.cancel(true);
}
private void GoToDesktop() {
Intent homeIntent= new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
private void LockTheScreen() {
ComponentName localComponentName = new ComponentName(this, DeviceAdminDemo.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)this.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// locking the device
localDevicePolicyManager.lockNow();
}
@override
public void onDestroy() {
// performs when user or system kills our service
StopPerformingServiceTask();
GoToDesktop();
LockTheScreen();
}
private void serviceTask() {
asyncTask = new MyTask();
asyncTask.execute();
}
class MyTask extends AsyncTask<Void, Void, Void> {
@override
protected Void doInBackground(Void... params) {
try {
for (;;) {
TimeUnit.SECONDS.sleep(SERVICE_TASK_TIMEOUT_SEC);
// check if performing of the task is needed
if(isCancelled()) {
break;
}
// Initiating of onProgressUpdate callback that has access to UI
publishProgress();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@override
protected void onProgressUpdate(Void... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "Ooops!!! Try to kill me :)", Toast.LENGTH_LONG).show();
}
}
// We should register our service in the AlarmManager service
// for performing periodical starting of our service by the system
private void startServiceStarter() {
Intent intent = new Intent(this, ServiceStarter.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, this.REQUEST_CODE, intent, 0);
if (pendingIntent == null) {
Toast.makeText(this, "Some problems with creating of PendingIntent", Toast.LENGTH_LONG).show();
} else {
if (serviceStarterAlarmManager == null) {
serviceStarterAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
serviceStarterAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + FIRST_RUN_TIMEOUT_MILISEC,
SERVICE_STARTER_INTERVAL_MILISEC, pendingIntent);
}
}
}
}
Everything here is also relatively simple.
At the start, service activates reset mechanism. If for some reason it is stopped, PendingIntent with information about our service will be created and transferred to the AlarmManager system service indicating restart timeout.
As a task, service creates a thread, which uses an infinite loop to periodically display the "Ooops !!! Try to kill me " message on the user’s desktop.
The service “autostarter” code (ServiceStarter.java)
"Autostarter" is presented by a standard BroadcastReceiver, in which the attempt to start the service is performed.
Receiver triggers according to timeout due to the AlarmManager service, because receiver was registered at the start of the service.
If the service is already running, then the second onCreate for it will not be called. And that is exactly what we need.
Code:
public class ServiceStarter extends BroadcastReceiver {
@override
public void onReceive(Context context, Intent intent) {
Intent serviceLauncher = new Intent(context, BackgroundService.class);
context.startService(serviceLauncher);
}
}
The DeviceAdmin component code (DeviceAdminComponent.java)
We need DeviceAdmin in order to:
• prohibit user to stop or uninstall the application;
• have the possibility to change the password and lock the device if user attempts to disable the DeviceAdmin component.
Also note that the administrator password is hardcoded as the "12345" string.
The onDisableRequested code works out after the confirmation of the DeviceAdmin deactivation, but before the deactivation itself.
Code:
public class DeviceAdminComponent extends DeviceAdminReceiver {
private static final String OUR_SECURE_ADMIN_PASSWORD = "12345";
public CharSequence onDisableRequested(Context context, Intent intent) {
ComponentName localComponentName = new ComponentName(context, DeviceAdminComponent.class);
DevicePolicyManager localDevicePolicyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE );
if (localDevicePolicyManager.isAdminActive(localComponentName))
{
localDevicePolicyManager.setPasswordQuality(localComponentName, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
}
// resetting user password
localDevicePolicyManager.resetPassword(OUR_SECURE_ADMIN_PASSWORD, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
// locking the device
localDevicePolicyManager.lockNow();
return super.onDisableRequested(context, intent);}}
Results
Thus, without using ROOT-permissions, incidents, or undocumented system features, we have managed to create the application that is practically impossible to be stopped or removed without knowing the administrator password. Although in some cases you can try to do it.
After studying this technique, we once again come to the conclusion that:
• it is almost always possible to find loopholes to circumvent any restrictions;
• it is strongly not recommended to install applications from untrusted sources. Especially if it requires the acceptance of the DeviceAdmin policies…
And what about you? Do you know a way to create a similar system?
Download sources at www(dot)apriorit(dot)com/dev-blog/355-create-deathless-android-applications.
This article is the intellectual property of Apriorit Inc. and their authors.
All materials are distributed under the Creative Commons BY-NC License.
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Creed14 said:
Very, very cool.
How would you go about doing the same when a phone was rooted and/ or the user had access to ADB?
Click to expand...
Click to collapse
I was going to ask the same thing. Is the protection absolute?
Sent from my SM-G920F using Tapatalk
Hello guys.
Thanks for questions and sorry for delay.
Do you ask exactly about ADB commands?
I am not sure all devices have similar behavior (but I really hope they do it), but my devices (moto X 1st gen; Android 4.4.4; both root and non-root) don't start adb demon on the device after it locks with some screen lock (pin/pattern/password).
So, you can't access to your device via adb commands if it has been previously detached from the PC.
Really? Cuz ADB is the most common suggestion for getting past a lockscreen if you forget the password. Not to mention from a softbricked phone, you should even be able to use it
You can try to overcome your own password via adb and share you results here (device brand, model, root/non-root, Android version etc.).
For the purity of the experiment I suggest to perform the next steps:
1) Unplug the device from the PC
2) Set your device screen lock password to "12345"
3) Reboot the device
4) Plug the device to the PC and try to unlock the device (or to find the correct password) using ADB.
The intrigue persists ...

Categories

Resources