Posts tagged ‘sdk’
I’ve heard a lot about CUDA, such as how it is 10,000% faster at cracking wireless passwords over a conventional program/hardware, but never really got around to testing it out before now. This post details the steps required to compile and setup CUDA 2.3 SDK and toolkit on ubuntu 9.10.
Downloads
You are required to have an Nvidia graphics driver (relatively new version) already installed. First download the CUDA toolkit and CUDA sdk from the Nvidia CUDA 2.3 download page.
Install the toolkit
# Make file executable chmod +x cudatoolkit_2.3_linux_64_ubuntu9.04.run # Run it as superuser sudo ./cudatoolkit_2.3_linux_64_ubuntu9.04.run
You now need to edit your .bashrc file in your home directory to include the paths (so your CUDA binaries can be found by the system)
export PATH=${PATH}:/usr/local/cuda/bin
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/cuda/lib64
Note if you are using 32bit then “lib64″ should be replaced with just “lib”
Install the SDK
# Make file executable chmod +x cudasdk_2.3_linux.run # Run it as normal user ./cudasdk_2.3_linux.run
You should now have a NVIDIA_GPU_Computing_SDK folder in your home directory. Change directory into the C folder inside this one.
cd NVIDIA_GPU_Computing_SDK/C
In this folder is a make file which will compile all the Nvidia SDK and all the demos, in order for this to work in ubuntu 9.10 (x64) you will need to install several dependencies. By installing these before attempting to make will save you a lot of time, if you are getting errors please scroll down to the problems section to see if they are already covered.
# Install the necessary libraries sudo apt-get install freeglut3 freeglut3-dev libx11-dev mesa-common-dev libxmu6
Making and running demos
You can then run the make command, once this is ran all of the executables will be placed in NVIDIA_GPU_Computing_SDK/C/bin/linux/released . We can check that our computer has an useable CUDA device install by running the deviceQuery program:
cd ~/NVIDIA_GPU_Computing_SDK/C/bin/linux/released ./deviceQuery
This should output something similar to the following:
# ./deviceQuery CUDA Device Query (Runtime API) version (CUDART static linking) There is 1 device supporting CUDA Device 0: "GeForce GTX 260" CUDA Driver Version: 2.30 CUDA Runtime Version: 2.30 CUDA Capability Major revision number: 1 CUDA Capability Minor revision number: 3 Total amount of global memory: 938803200 bytes Number of multiprocessors: 27 Number of cores: 216 Total amount of constant memory: 65536 bytes Total amount of shared memory per block: 16384 bytes Total number of registers available per block: 16384 Warp size: 32 Maximum number of threads per block: 512 Maximum sizes of each dimension of a block: 512 x 512 x 64 Maximum sizes of each dimension of a grid: 65535 x 65535 x 1 Maximum memory pitch: 262144 bytes Texture alignment: 256 bytes Clock rate: 1.47 GHz Concurrent copy and execution: Yes Run time limit on kernels: Yes Integrated: No Support host page-locked memory mapping: Yes Compute mode: Default (multiple host threads can use this device simultaneously) Test PASSED
Now that we can see CUDA is successfully installed and a suitable device is found we can run some of nvidia’s more ascetically pleasing demos:
./fluidsGL
./smokeParticles
./particles
./postProcessGL
Problems
libxi (Nvidia forum link) make[1]: Leaving directory `/home/mat/NVIDIA_GPU_Computing_SDK/C/common' make[1]: Entering directory `/home/mat/NVIDIA_GPU_Computing_SDK/C/common' In file included from ./../common/inc/paramgl.h:24, from src/paramgl.cpp:19: ./../common/inc/GL/glut.h:60:20: error: GL/glu.h: No such file or directory make[1]: *** [obj/release/paramgl.cpp.o] Error 1 make[1]: Leaving directory `/home/mat/NVIDIA_GPU_Computing_SDK/C/common' make: *** [lib/libparamgl.so] Error 2
sudo apt-get install freeglut3 freeglut3-dev libx11-dev mesa-common-dev
/usr/include/bits/mathcalls.h:350: error: inline function ‘int __signbitf(float)’ cannot be declared weak /usr/include/bits/mathcalls.h:350: error: inline function ‘int __signbitl(long double)’ cannot be declared weak /usr/include/bits/mathinline.h:36: error: inline function ‘int __signbitf(float)’ cannot be declared weak /usr/include/bits/mathinline.h:42: error: inline function ‘int __signbit(double)’ cannot be declared weak /usr/include/bits/mathinline.h:48: error: inline function ‘int __signbitl(long double)’ cannot be declared weak /usr/local/cuda/bin/../include/math_functions.h:442: error: inline function ‘int __signbitl(long double)’ cannot be declared weak make[1]: *** [obj/release/particleSystem.cu.o] Error 255 make[1]: Leaving directory `/home/mat/NVIDIA_GPU_Computing_SDK/C/src/particles' make: *** [src/particles/Makefile.ph_build] Error 2
The problem is due to having gcc 4.4 installed rather than 4.3, it is possible to install the older version of this compiler but it is simpler to modify common/common.mk and add the following extra flag (Nvidia forum link):
# Change: NVCCFLAGS += --compiler-options -fno-strict-aliasing # To: NVCCFLAGS += --compiler-options -fno-strict-aliasing --compiler-options -fno-inline
and change the -O2
# Change: COMMONFLAGS += -O2 # To: COMMONFLAGS += -O0
The two remaining errors you may encounter are very similar and arrise from missing libraries:
libxi (Nvidia forum link)
/usr/bin/ld: cannot find -lXi collect2: ld returned 1 exit status make[1]: *** [../../bin/linux/release/particles] Error 1
sudo apt-get install libxi-dev
libxmu (Nvidia forum link)
/usr/bin/ld: cannot find -lXmu collect2: ld returned 1 exit status make[1]: *** [../../bin/linux/release/particles] Error 1
sudo apt-get install libxmu-dev libxmu6
When creating any non-trivial program using a versioning system is essential, especially when working in part of a group. This guide aims to be a quick tutorial to the SVN (subversion) tool for versioning and how to use it with an android project.
Assumptions
-
You will need SVN installed on your computer. This can be done using your package manager or by the following command in ubuntu / debian based systems:
sudo apt-get install subversion
-
You already have an SVN repository configured. If not please view a tutorial like this or if you have a nice webhost like me (thanks dreamhost
) there may be a simple tool to do this automatically for you in your panel.
Note
Don’t include the files inside /bin or /gen as they are just build from the source code and will simply fill up a lot space in your SVN. But do include the folders themselves as the project will fail to build without them.
Command line (recommended)
For SVN, I am a great fan of the command line. From the few SVN GUI applications that I have used in the past I can recommend Turtoise SVN for windows and kdesvn for linux (kde) but I still prefer the command line.
The following code will checkout the project from your server. This will create a new folder called “projectname” on your computer and download the project from your server (at this point it is most likely an empty folder).
# Checkout the SVN directory svn co svn.yourdomain.com/projectname projectname
You can then copy or create your android project in this directory. In our project folder there are two folders which contain generated files (as opposed to source files) there is no point uploading these to the svn as you will simply take up space and bandwidth. Before you decided to upload your changes to the server you should empty the bin and gen folders:
# Empty bin and gen folders rm -rf ./projectname/bin/* rm -rf ./projectname/gen/*
Each time you add a new file to the project you will need to add (`svn add filename` for single files or `svn add *` for all files):
# Tell SVN we want to be versioning these files svn add projectname/*
When you are happy with your changes you can commit (`svn commit -m “message”`) your changes to the svn to create a new version, it is mandatory to include a message with each revision and it is best to be as detailed as possible with the changes made. This makes it much easier to hunt down where a bug or regression was introduced.
# Save the changes and upload to repository svn commit -m "Initial import of projectname"
Each time you commit or wish to upgrade what is stored locally to the latest version on the server you need to use the following:
# Update the locally stored version svn update projectname
Further points
Eclipse has a plugin to manage SVN download and install instructions can be found here.
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.
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.
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));
}
}
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.
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.
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:
Ref
anddev.org
This post builds upon the ideas shown in this post to create a complete function that will do the follow:
- Accept a string input for the message
- Try to open twidroidpro to send this tweet
- If failed, try to open twidroid to send this tweet
- If failed, bring up a list of applications that can send this information
- Return a boolean indicating success of displaying the intent
Code
public boolean intentTwitter(String message){
// Boolean to show if we succeeded or not
// we assume we did until proven otherwise.
boolean success=true;
//Try twidroidpro first
Intent intent = new Intent("com.twidroidpro.SendTweet");
intent.putExtra("com.twidroidpro.extra.MESSAGE", message);
intent.setType("application/twitter");
try{
startActivityForResult(intent, 1);
}
catch(ActivityNotFoundException e){
success=false;
}
// Then twidroid if we failed
if (!success){
success=true;
intent = new Intent("com.twidroid.SendTweet");
intent.putExtra("com.twidroid.extra.MESSAGE", message);
intent.setType("application/twitter");
try{
startActivityForResult(intent, 1);
}
catch(ActivityNotFoundException e){
success=false;
}
}
//Then send general intent if we failed again
if (!success){
success=true;
try {
intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, d);
intent.setType("application/twitter");
startActivity(Intent.createChooser(intent, null));
} catch (ActivityNotFoundException e) {
success=false;
}
}
// return indicating if we were successful in bringing up an intent
// of some description
return success;
}
Example
Below is a screenshot from the wordcube (available on market) application using this function to make the application interact with twitter.
What’s next?
In a future post I will be demonstrating how to interact with the android market, this can be use in conjunction with something similar to above to try and run a program and if the program is not installed the user can be taken to the market to download a program.
A soundboard is a very simple application to make, and I was given the idea to make a counter-strike 1.6 version by a friend. It seemed like a good idea as no one had made one yet, and it’s quite hard to find something that hasn’t already been done before.
counter-strike 1.6 soundboard
The buttons are aligned in a grid view, with the buttons made transparent so that the background can be seen.

screenshot of counter-strike 1.6 soundboard

screenshot of counter-strike 1.6 soundboard
I am very pleased with the final look of the app, however it was getting poor reviews due to people wanting to save the sounds for use as a ringtone. To alleviate this problem I have updated the app to have this option as a context menu avaliable by long pressing on a button. This will then save the file on the sd card and update the mediastore to tell android a new ringtone and notification has been added.
The code to load a ringtone into android from an application is shown below. If you see any problems with this code, or have an improvements please let me know!
File k = new File(path, filename); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, filesnames[pos]); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav"); 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);
Ratings, reviews, feedback and feature requests are most welcome.
Android Market Link (For android phones)
Below are some code snippets for sending messages to twitter from your application by utilizing a twitter application.
The following code will create a new intent(a request to android for something to happen) for the twidroid application and pass it the message we wish to send. It is important to set the type of the intent as it will fail without it (from at least android 1.5). It will then start the activity and we use a try/catch encase twidroid is not found.
Intent intent = new Intent("com.twidroid.SendTweet");
intent.putExtra("com.twidroid.extra.MESSAGE",
"@stealthcopter Example tweet from android application");
intent.setType("application/twitter");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
/* Handle Exception if Twidroid is not installed */
Toast.makeText(this, "Twidroid not found.", Toast.LENGTH_SHORT).show();
}
But what if someone has a different twitter application installed? this can be solved by offering the user a choice of application to open.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,
"@stealthcopter Example tweet from android application");
intent.setType("application/twitter");
try {
startActivity(Intent.createChooser(intent, null));
}
catch (ActivityNotFoundException e) {
/* Handle Exception if no suitable apps installed */
Toast.makeText(this, "No suitable apps found.", Toast.LENGTH_SHORT).show();
}
By combining these two solutions we can make the choice dialog only pop up if the system cannot find the twidroid application. This can be then taken even further by asking the user if they wish to visit the market place to install a twitter application if none is found.
new AlertDialog.Builder(WordCube.this)
.setTitle("Get Twitter")
.setMessage("No twitter Application not found. Goto market and install one now?")
.setIcon(R.drawable.logo)
.setNegativeButton(R.string.dialog_no, null)
.setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intentMarket("market://search?q=twitter");
}
})
.show();
Where intentMarket() is defined a to open up the market and search for the specified application passed to it as a string.
public void intentMarket(String url){
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
i.setData(u);
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
toastMessage("Market not found.");
}
}
Below shows two screenshots from the wordcube application. This application is avaliable for android, see here for more information and download link (or visit market on your android device).
Update: This is now taken into a complete function in this post.









