Skip to content

Archive for January, 2010

Bash: Script to find active computers in a subnet using ping

Jan 27 10
by mat

The following is a simple bash script that will scan each ip address in a give subnet and report if they are alive (or accepting ping requests). The code creates processes for each ping so that it completes quickly rather than scanning each ip address sequentially.

Create a text file called “pinger.sh” and paste the following into it:

#!/bin/sh

: ${1?"Usage: $0 ip subnet to scan. eg '192.168.1.'"}

subnet=$1
for addr in `seq 0 1 255 `; do
#   ( echo $subnet$addr)
( ping -c 3 -t 5 $subnet$addr > /dev/null && echo $subnet$addr is Alive ) &
done 

Save and close, then it can be called from the command line like so:

sh pinger.sh 192.168.1.

This will scan from 192.168.1.0 to 192.168.1.255 and will return something like the following:

192.168.1.1 is Alive
192.168.1.105 is Alive
192.168.1.112 is Alive
192.168.1.149 is Alive

Android: Unreal Tournament SoundBoard

Jan 27 10
by mat

Following the popularity of my counter-strike 1.6 soundboard and requests for the “HEADSHOT” noise for it, I have created an Unreal Tournament soundboard (from which the headshot sound originates).

Sounds:
Features all of the following sounds:

  • dominating
  • double kill
  • first blood
  • god like
  • headshot
  • holy shit
  • killing spree
  • ludicrous kill
  • mega kill
  • monster kill
  • multi kill
  • play
  • rampage
  • ultra kill
  • unstoppable
  • wicked sick

Screenshots
The following are screenshots from the application:

unreal tournament soundboard

unreal tournament soundboard


Unreal tournament soundboard

Unreal Tournament Soundboard 2

Download
Unreal Tournament SoundBoard can be downloaded from the market on your android phone either by searching or following the android link below. Alternativly you can download the apk file from this website using the download link

Android: UTsoundboard
Download: UTsoundboard download

If you enjoyed this please leave feedback for me either here or on the market. Comments, suggestions and constructive criticism is also welcome.

Android: Saving a sound file to SD from resource and setting as ringtone

Jan 26 10
by mat

Quite a few people have been asking how to save a file to the SD card in order to register it as a ringtone. The following example creates a function that will save a resource to the SD card (ie: from R.raw.soundfile to /sdcard/media/audio/ringtones/soundfile.ogg) and register it as a ringtone.

I have split this example into two parts, the first part goes through the code a section at a time with a brief explanation of what it does, the second half is just the code that you can copy and paste and then edit to your hearts content.

Parts

We first setup our function to return a boolean depicting if we have failed or if we are successful. We accept in an integer which corresponds to the raw sound file.

public boolean saveas(int ressound){

}

So this function would be called in the following fashion:

saveas(R.raw.soundfile);

or utilising its boolean return:

if (saveas(R.raw.soundfile)){
// Code if successful
}
else
{
// Code if unsuccessful
}

The following chunk of code creates an inputstream from the raw sound resource and loads it into a buffer. We add in the mandatory try/catch clause around these operations and return false if an exception is raised (to indicate failure to the rest of our program and to prevent trying to continue act upon this sound).

 byte[] buffer=null;
 InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
 int size=0;

 try {
  size = fIn.available();
  buffer = new byte[size];
  fIn.read(buffer);
  fIn.close();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  return false;
 }

The following saves the buffer to a file on the SD card. It first ensures the folder exists and if not it is created. Then as before the writing operations are surrounded with try/catches

 String path="/sdcard/media/audio/ringtones/";
 String filename="examplefile"+".ogg";

 boolean exists = (new File(path)).exists();
 if (!exists){new File(path).mkdirs();}

 FileOutputStream save;
 try {
  save = new FileOutputStream(path+filename);
  save.write(buffer);
  save.flush();
  save.close();
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  return false;
 } catch (IOException e) {
  // TODO Auto-generated catch block
  return false;
 }    

The following code sends an intent to tell the Media Scanner that we have added a new file, and sets up its properties in the media database:

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

 File k = new File(path, filename);

 ContentValues values = new ContentValues();
 values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
 values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
 values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
 values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
 values.put(MediaStore.Audio.Media.IS_ALARM, true);
 values.put(MediaStore.Audio.Media.IS_MUSIC, false);

 //Insert it into the database
 this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

Final code
Putting all this code together gives us our final functions:

public boolean saveas(int ressound){
 byte[] buffer=null;
 InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
 int size=0;

 try {
  size = fIn.available();
  buffer = new byte[size];
  fIn.read(buffer);
  fIn.close();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  return false;
 }

 String path="/sdcard/media/audio/ringtones/";
 String filename="examplefile"+".ogg";

 boolean exists = (new File(path)).exists();
 if (!exists){new File(path).mkdirs();}

 FileOutputStream save;
 try {
  save = new FileOutputStream(path+filename);
  save.write(buffer);
  save.flush();
  save.close();
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  return false;
 } catch (IOException e) {
  // TODO Auto-generated catch block
  return false;
 }    

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

 File k = new File(path, filename);

 ContentValues values = new ContentValues();
 values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
 values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
 values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
 values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
 values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
 values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
 values.put(MediaStore.Audio.Media.IS_ALARM, true);
 values.put(MediaStore.Audio.Media.IS_MUSIC, false);

 //Insert it into the database
 this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);


 return true;
}

Comments, suggestions etc. are always welcome. Hope this has been helpful.

Android: Opening a webpage in your app using Intents

Jan 25 10
by mat

Opening up a website from an application in android is very simple thanks to “Intents”. An Intent is a request to android use an application to preform a task. The code below shows a very simple example of launching a browser to go to the wordcube website.

Context context = getApplicationContext();
String url = "http://www.stealthcopter.com/wordcube";
Intent i = new Intent(Intent.ACTION_VIEW); 
Uri u = Uri.parse(url); 
i.setData(u); 
try {
  // Start the activity
  startActivity(i);
} catch (ActivityNotFoundException e) {
  // Raise on activity not found
  Toast toast = Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}

As pointed out in the comments, the context can be replaced by the activity itself, such as TestApp.this. eg:

Toast toast = Toast.makeText(TestApp.this, "Browser not found.", Toast.LENGTH_SHORT);

We have surrounded the activity with a try/catch which will be raised if android cannot find an application that will accept this intent, in this case a web-browser. It is highly unlikely that an android phone will not have a web-browser installed but it is a good practise to get into.

Android: WordCube – Daily puzzle game

Jan 23 10
by mat

Due to the success (and small amount of addiction) of my browser-based wordcube game (see here), I decided to make a WordCube application for android.

Features

  • Anagram / Wordsearch based puzzle
  • Small file size (~100kb) and footprint
  • Updated daily
  • Share score with twitter integration (compete with friends)
  • Saves your last attempts so you can continue at later time
  • This also means you can continue your last game offline
  • Several achievements can be unlocked (more to come, also looking for suggestions for achievements)

wordcube screenshot

screenshot of wordcube

Gameplay
Find as many words as possible using letters from the grid. The words must be 4 letters or more, contain the central letter and each letter may not be used more than once. There is at least one word that uses all of the letters in the cube.

The main interface is by tapping the letters in order to construct a word, but keyboards (and on screen keyboards) are also supported.

wordcube screenshot 2

Another wordcube screenshot

Twitter Integration
Once you have attained all the words that you can, you can post your score to twitter and then compare with your friends to see how they did in comparison. In order to use this feature you need to have a twitter client installed, I would recommend twidroid.

wordcube twitter integration

Twitter integration in wordcube

Download
WordCube can be downloaded from the market on your android phone either by searching for wordcube or following one the two android links below. To download the WordCube app from this website, follow the Web link.

Android: WordCube Free
Android: WordCube Pro (only £1)
Web: WordCube Free

The pro version is available for £1, with the money going to support the developer and the development and maintenance of this application. The pro version features all of the latest features and in the near future will support personal statistics to keep track of performance.

If you enjoyed this please leave feedback for me either here or on the market. Comments, suggestions and constructive criticism is also welcome.

Stealthbomber pillow (not quite a stealthcopter…)

Jan 22 10
by mat

Using a V-Shaped pillow extended by your feet kinda makes it look like a stealthbomber:

stealthcopter pillow

stealthbomber pillow

Android: Eclipse and problems with dynamic tables (adding rows)

Jan 20 10
by mat

When using TableLayout with LayoutParams Eclipse will automatically (and wrongly) add the following import:

import android.view.ViewGroup.LayoutParams;

However if you try to use this you will notice that nothing changes. You need to replace the import with the ollowingL

import android.widget.TableRow.LayoutParams;

Now if you rerun your code, you will see that your tables are updating. See below for an example of the code to generate a table

int sizey=10;
int sizex=10;
int btnwidth=24;
TableLayout tl = (TableLayout)findViewById(R.id.MyTableLayout); 

for (int y=0;y<sizey;y++){

// Rows
TableRow tr = new TableRow(this); 
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

//Cells
for (int x=0;x<sizex;x++){
// Create new cell
	// new button
	Button b = new Button(this); 
	b.setText(x+""+y); 
	b.setLayoutParams(new LayoutParams( 
		LayoutParams.FILL_PARENT, 
		LayoutParams.WRAP_CONTENT));
	b.setHeight(btnwidth);
	b.setBackgroundResource(R.drawable.btn_blue);
	b.setOnClickListener(new PegOnClickListener(y,x));
	// add button to row
	tr.addView(b); 
	}
// add row to layout
tl.addView(tr,new TableLayout.LayoutParams( 
LayoutParams.FILL_PARENT, 
LayoutParams.WRAP_CONTENT));
}
}

Bash: Script to convert .flv to mp3

Jan 18 10
by mat

Flash Video (.FLV) is currently a very popular format of online videos, inparticular youtube. This post explains how to use a simple script to extract the sound from a flash video file and turn it into an mp3.

In order for the script to work you will need to download ffmpeg (to decode the video) and lame (to encode the mp3). This can be achieve in ubuntu by opening a terminal and running the following or alternatively you can use your package manager GUI to search and download the packages for you.

sudo apt-get install ffmpeg lame

You then need to create a new file named “flv2mp3.sh” and paste the following into it using your preferred text editor (which hopefully isn’t VI). Save the file and then change the file permissions so that it is executable (by running:`chmod a+x flv2mp3.sh` in the terminal or via the gui in you file browser)

#!/bin/sh
# this script should convert files from FLV to WAV and then to MP3
echo " "
echo "  Welcome to FLV to MP3 converter!  version 0.1"
echo " "
infile_name="$@"
# exit if the user did not enter anything:
if [ -z "$infile_name" ]; then
    echo " "
    echo "You did not tell me the file name, so I will exit now."
    echo " "
    exit
fi
echo " "
ffmpeg -i "$infile_name" -acodec pcm_s16le -ac 2 -ab 128k -vn -y "${infile_name%.flv}.wav"
lame --preset cd "${infile_name%.flv}.wav" "${infile_name%.flv}.mp3"
rm "${infile_name%.flv}.wav"
echo " "
echo "OK. I'm done! Have fun!"
echo " "
exit 

You should now be able to convert a flashvideo into an mp3 by running the following command (changing the filenames to fit your purpose):
sh flv2mp3.sh videofilename.flv

Extra: Youtube
In linux it might be worth noting that youtube downloads the flv’s to your /tmp folder and you can easily copy them or convert to mp3’s (Ensure video is completly finished loading).

Also there is an application called ‘youtube-dl’ which can be installed from the repositories

sudo apt-get install youtube-dl

and then run using

youtube-dl http://www.youtube.com/video_to_borrow

Of course it’s up to your moral guidance to decide what you can and can’t download.

Android: Blurring and dimming background windows from dialogs

Jan 17 10
by mat

The android SDK has lots of nice goodies built in to make your applications look sexier. One such feature is the blurring of windows. This effect looks particularly nice if a background window is blurred while a dialog box is shown above which can really make it stand out. Below shows the application such an example; on the left is the default about box (for WordCube Pro) and on the right is with added blur and no dimming.

android blur dim, before, after

android bluring and dimming effect before and after

I am using the AlterDialog.Builder to create my dialog, however this method will work with all kinds of dialog providing you can access it via getWindow.

   dialog = new AlertDialog.Builder(WordCube.this)
   .setTitle(WordCube.this.getResources().getString(R.string.app_name))
   .setMessage(s)
   .setIcon(R.drawable.logo)
   .setPositiveButton(R.string.btn_close, null)
   .show();

Below shows the code needed to add blur and remove dimming of the background (as I think the blur looks nicer when the background is well lit).

WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=0.0f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

The blur is simply created using the last line (line 4) which sets a flag for the dialog telling android that we want windows below this one to be blurred. To achieve the dimming, we need to retrieve the layout parameters for the dialog window, set the dim amount to zero, update these parameters with setAttributes (lines 1-3).

Any comments, questions, or improvements please let me know.

Android: Requesting root access in your app

Jan 17 10
by mat

This snippet shows how root access can be requested inside an application in order to write a file into a place we do not have permission to access usually. Requesting root access will only work if your phone allows it, or it has been ‘rooted’ (hacked to allow superuser permissions).

Process p; 
try { 
   // Preform su to get root privledges
   p = Runtime.getRuntime().exec("su"); 
   
   // Attempt to write a file to a root-only 
   DataOutputStream os = new DataOutputStream(p.getOutputStream()); 
   os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
   
   // Close the terminal
   os.writeBytes("exit\n"); 
   os.flush(); 
   try { 
      p.waitFor(); 
           if (p.exitValue() != 255) { 
        	  // TODO Code to run on success
              toastMessage("root");
           } 
           else { 
        	   // TODO Code to run on unsuccessful
        	   toastMessage("not root");    
           } 
   } catch (InterruptedException e) { 
      // TODO Code to run in interrupted exception
	   toastMessage("not root"); 
   } 
} catch (IOException e) { 
   // TODO Code to run in input/output exception
	toastMessage("not root"); 
}

Where my “toastMessage” is just a function which creates a toast to display on the screen. On phones with superuser permissions installed (root access) this will display a dialog asking the user to allow or deny the application permission to have root access:

android root access dialog

android request root access dialog

Ref
anddev.org