How to execute a shell command from android app

To execute a shell command from your android app you can grab the standard input of the su process just launched by Runtime.getRuntime().exec(“su”) and write down the command there, otherwise you are running the commands with the current UID.

With the following code you can excute the screenrecord command to grab your screen to a mp4 video file (Works on Android 4.4 API level 19 and higher). There are many othe commands you can execute. You can find some of them at https://developer.android.com/tools/help/shell.html

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

Source:
http://stackoverflow.com/questions/20932102/execute-shell-command-from-android

How to turn on/off (enable/disable) GPS in Android

If you want to develop an Android app to turn on/off GPS you can use the following code snippets.

// turn on gps
public void turnGPSOn()
{
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);


    }
}

// turn off gps
public void turnGPSOff()
{
    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        this.ctx.sendBroadcast(poke);
    }
}

Source:
http://stackoverflow.com/questions/15426144/turning-on-and-off-gps-programmatically-in-android-4-0-and-above

Simple standalone http server made with esp8266 and nodemcu

The following code is a standalone http server made with esp8266 and nodemcu written in lua.
The esp8266 is in wifi.SOFTAP mode (SoftAP is an abbreviated term for “software enabled access point.” This is software enabling a computer which hasn’t been specifically made to be a router into a wireless access point. It is often used interchangeably with the term “virtual router”.)

You can connect connect your smarthone with the esp8266 direct without any router or other network infrasructure. Just load the following code as init.lua on you eso8266 flash ram and reset.

print("WIFI control")

wifi.setmode(wifi.SOFTAP)
print("ESP8266 mode is: " .. wifi.getmode())
cfg={}
cfg.ssid="esp8266"
cfg.pwd="password"

if ssid and password then
  print("ESP8266 SSID is: " .. cfg.ssid .. " and PASSWORD is: " .. cfg.password)
end

wifi.ap.config(cfg)
print("ESP8266 AP IP now is: " .. wifi.ap.getip())

sv=net.createServer(net.TCP,30)
sv:listen(80,function(c)
c:on("receive", function(c, pl)
  print(pl)
  c:send("HTTP/1.1 200 OK\r\n") 
  c:send("Connection: close\r\n\r\n")
  c:send(" ")
  c:send(" ")
  c:send("

ESP8266 Wireless control setup

") majorVer, minorVer, devVer, chipid, flashid, flashsize, flashmode, flashspeed = node.info(); c:send("NodeMCU "..majorVer.."."..minorVer.."."..devVer.."

") bat = adc.readvdd33()/1000 c:send("Battery "..bat.."

") remain, used, total=file.fsinfo() c:send("File system info:
Total : "..total.." Bytes
Used : "..used.." Bytes
Remain: "..remain.." Bytes
") c:close() end) end)

The following circuit shows the min. configuration for your esp8266 to get the best stability.
ESP8266_improved_stability

If you ues a board with GPIO16 (Not ESP-01) you can connect the GPIO16 with REST to use the dsleep function. Otherwise your esp8266 will not wake up after execution of dsleep.

How to set mobile input types in HTML?

Mobile devices have virtual keyboards. There is only limited space on the display to show the keyboard, so it will be helpful to the user to see only the needed keys. Using the right input type will dramatically improve the mobile experience.

There are many different input types available for html pages. Here are my favorites.

Input type text

The most common input type used. This will show the default keyboard on mobile devices.


Input type email

The input type email will show a virtual keyboard with easy access to the AT-Sign (@), the dot and sometimes there will be shown the most common top level domains, so you don’t have to enter “.com” letter by letter. The difference to the text input type is only marginal, but the mobile user experience will increase dramatically if you use the input type on the right field.


Input type tel

With the input type tel you can make it easy to enter a telephone number because you will get a virtual keyboard with a numeric keypad which includes everything you need to enter a phone number like sharp (#) or plus (+).


Input type number

The mobile input type “number” is correct if you have to enter numbers only. It is different from the input type tel and is the right type to enter numbers of barcodes, counters or anything else mainly containing digits but i think this type shouldn’t be using very often because in most cases tel will work better.


Input type password

If you ever made a login form you should know about it and I don’t want to describe it here, because there are millions of good descriptions about this input type in the World Wide Web.


Input type date

The name of the input type is date and this is what you can enter here. You don’t have to implement a JavaScript calendar widget or something else. Just set the tags attribute type to date and the mobile will do the rest for you. I like it.


Input type datetime

It is like the input type date, but it adds the time to the input. So you can enter date and time into your input field. Just replace the tag attrubte type from date to datetime and you have a input field for date and time.


Input type search

If your input field is a search field, you can use this type. It will show the (nearly) regular virtual keyboard with on exception. You get a search button direct on the virtual keyboard if you use this mobile input type. It is quite helpful and I use it often if I need a search function in my form.

 

Note: Some devices and virtual keyboards do not support every mobile input type. But If you user iOS or Android with a common keyboard, I’m sure you will get the right keyboard for your input type. And there are more…. but the above are the main types (IMHO).

Disable text selection with CSS

Yes, it is possible to disable the text selection with a simple line of CSS.

The user-select property is a new CSS3 property. Using user-select enables web and app developers to control the ability to select text. Most browsers (With CSS3 support), can do this by using variations on the CSS3 user-select property. The user-select property controls the actual Selection operation (Text and Images). This won’t have effect on the visible content, except in textboxes. The content of the element and all sub-elements will not be able to be selected.

.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Selectable text.

Unselectable text.

For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML. But this property isn't inherited to child elements, meaning you have to put the unselectable attribute in the start tag of every element inside the tag.

Text selection is disabled here.

At least there is a additional JavaScript solution for the IE.

Text selection is disabled via JavaScript in IE here.

Note:
Disable text selection with CSS is non-standard and is not on a standards track. Avoid using it on production sites facing the Web. It will not work for every user.

Links:
http://stackoverflow.com/
https://developer.mozilla.org/

How to get the version of your Android application from AndroidManifest.xml?

There are two parts of the version in AndroidManifest.xml.

  • android:versionCode
  • android:versionName

In your AndroidManifest.xml the versionCode is a number, and every version you want to submit to google play needs to have a higher number then the last. VersionName is just a string, and can be anything you want it to be. In VersionName you can define your app as “1.0” or “2.5.1.12982” or “Test Version” or whatever.

To get the android:versionCode and the android:versionName you can use the following code snippet where context is your actual context. If you execute this code in your Activity you can remove the “context.” from “context.getPackageManager()”. Because the Activity is a indirect Subclasses of Context.

Context context = getApplicationContext();
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String versionName = pInfo.versionName;
String versionCode = pInfo.versionCode;

Note: Other known Subclasses of Context are:

AbstractInputMethodService
AccessibilityService
AccountAuthenticatorActivity
ActionBarActivity
Activity
ActivityGroup
AliasActivity
AppCompatActivity
Application
BackupAgent
BackupAgentHelper
CarrierMessagingService
DreamService
ExpandableListActivity
FragmentActivity
HostApduService
InputMethodService
IntentService
IsolatedContext
JobService
LauncherActivity
ListActivity
MediaBrowserService
MediaRouteProviderService
MockApplication
MultiDexApplication
MutableContextWrapper
NativeActivity
NotificationCompatSideChannelService
NotificationListenerService
OffHostApduService
PreferenceActivity
PrintService
RecognitionService
RemoteViewsService
RenamingDelegatingContext
Service
SettingInjectorService
SpellCheckerService
TabActivity
TestActivity
TextToSpeechService
TvInputService
VoiceInteractionService
VoiceInteractionSessionService
VpnService
WallpaperService

If you are not in in a class that is a subclass of Context you have to identify your context to get the version from your AndroidManifest.xml.

Remove uncommitted changes from your working directory in GIT

There is a easy solution to remove all uncommitted changes from your working directory in GIT

git fetch origin
git reset --hard origin/master

Note: After executing this command, all uncommitted changes will be removes from your working directory. If you want to save the current work before removing all uncommitted changes, you can do:

git commit -a -m "Backup my work before reset"
git branch backup

Now your work is saved on the branch “backup” in case you decide you want to backup your work to look at it later or diff it.

Source: http://stackoverflow.com/

Capture screenshot in Java (AWT)

In Java there is a easy was to capture screenshots. The following captureScreenshot method will capture a screenshot of the display of your screen and save it to the disk.

public void captureScreenshot(String filename) 
   throws Exception 
{
   java.awt.Dimension size = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
   java.awt.Rectangle rectangle = new java.awt.Rectangle(size);
   java.awt.Robot robot = new java.awt.Robot();
   java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle);
   javax.imageio.ImageIO.write(image, "png", new java.io.File(filename));
}

If you want to create a screenshot of a specific part of your screen, you have to modyfy the rectangle. You can do this with rectangle .setBounds(int x, int y, int width, int height).

Rectangle API: http://docs.oracle.com/

Note: This will need “java.awt”. So you cannot run this code on Android devices, because there is no java.awt package available. Also note, that you have to run a X-Server on linux to execute this. If you try to execute this on a linux server without X-Server, you will not be able to capture screenshot of your terminal.
On Windows this is not a problem. The capture screenshot method will work on windows even if you are not the Administrator.

How to get the name of the current method in Java

There is a simple solution, to get the name of the current method in Java. It uses the stack trace to get the name of the mehod. It works with different virtual machines like oracle, dalvik (Android), Open JDK, etc.

String name = Thread.currentThread().getStackTrace()[1].getMethodName();

But don’t use this in time-critical code, because working with the StackTrace is not recommended for high performcnce activities.

Source: http://stackoverflow.com/

How to create random human readable passwords in PHP

To generate random readable passwords you can combine words, letters and special chars. The words can come from a wordlist array. For example you can use the list of the 10,000 most common English words in order of frequency, as determined by n-gram frequency analysis of the Google’s Trillion Word Corpus.

In the exmaple the words are taken from a static array, but you can use the google-10000-english.txt file with the php file() function which reads an entire file into an array. The generated password will contain one or more of the words in the list, depending on the length parameter. If you execute

random_readable_pwd(10);

you will get a random readable password with a length of 10 chars, but you can adjust the parameter to get a password with a different length.

function random_readable_pwd($length=10){

    // the wordlist from which the password gets generated
    // (change them as you like)
    $words = 'AbbyMallard,AbigailGabble,AbisMal,Abu,Adella,TheAgent,AgentWendyPleakley,Akela,AltheAlligator';

    $phonetic = array("a"=>"alfa","b"=>"bravo","c"=>"charlie","d"=>"delta","e"=>"echo","f"=>"foxtrot","g"=>"golf","h"=>"hotel","i"=>"india","j"=>"juliett","k"=>"kilo","l"=>"lima","m"=>"mike","n"=>"november","o"=>"oscar","p"=>"papa","q"=>"quebec","r"=>"romeo","s"=>"sierra","t"=>"tango","u"=>"uniform","v"=>"victor","w"=>"whisky","x"=>"x-ray","y"=>"yankee","z"=>"zulu");

   // Split by ",":
    $words = explode(',', $words);
    if (count($words) == 0){ die('Wordlist is empty!'); }

    // Add words while password is smaller than the given length
    $pwd = '';
    while (strlen($pwd) < $length){
        $r = mt_rand(0, count($words)-1);
        $pwd .= $words[$r];
    }

    $num = mt_rand(1, 99);
     if ($length > 2){
        $pwd = substr($pwd,0,$length-strlen($num)).$num;
    } else {
        $pwd = substr($pwd, 0, $length);
    }

   $pass_length = strlen($pwd);
   $random_position = rand(0,$pass_length);

   $syms = "!@#%^*()-?";
   $int = rand(0,9);
   $rand_char = $syms[$int];

   $pwd = substr_replace($pwd, $rand_char, $random_position, 0);

    return $pwd;
}

Source: http://stackoverflow.com/