Posts Tagged ‘Android’
04
May

In Cocos2D Android, positioning elements is a very tedious process. In most cases, the absolute position that we give will not be used as it is. You can fix this issue by setting the following properties of that element :

 

Consider a CCSprite object, mySprite. Now you have to set the following properties of that object before positioning it absolutely

 

mySprite.setAnchorPoint(0, 0);

mySprite.setRelativeAnchorPoint(true);

 

Now if you give the absolute position for the object, it will work fine.

, , , , ,

30
Apr

If your phone doesnt show anything when you connect an external usb disk then you need to reconfigure the USB Adapter’s pin outlet.

1 VCC Red +5 V
2 D− White Data −
3 D+ Green Data +
4 ID none Mode Identification
5 GND Black Ground

LapDock:
+5V and GND connected directly to the battery of the LapDock, TX+RX connected to the integrated USB HUB.

Docking Station:
+5V and GND connected directly to external power (5V AC), TX+RX connected to the integrated USB HUB.

Oh, in BOTH, for enabling the Host Mode, pins 4 and 5 are shortcircuited, exactly as the USB OTG specifications.

, ,

30
Apr

Tethering: the black sheep of rooting capabilities. Beloved by users who don’t want to break the bank by having to spring for another connection; hated by mobile ISP’s whose network is drained by it. In the ongoing struggle between providers and powerusers a new development has occured: reverse tethering.

What is reverse tethering?

Tethering is the ability to surf on your pc using the 3g of your phone
Reverse tethering is the opposite : surf on your phone using the ADSL of your PC.

The app is still in the early stages, and there are a couple of bugs that need to be worked out (like not being able to download from Market) but so far looks promising. The developer is also accepting feedback on models not currently listed under tested devices. So head on over to the thread here, plug in your phone, and show it some internet love.

,

30
Apr
find ! -iname "abc" -maxdepth 1 -depth -print0 | sed '$d' | xargs -0 rm -r; 

Notes:

  • -depth — reverses the output (so you dont delete sub-dirs first)
  • -maxdepth 1 — kind of voids the use of -depth, but this says only output contents of the current directory and not sub-dirs (which are removed by the -r option anyway)
  • -print0 and -0 — splits on line feeds instead of white space (for dirs with space in the name)
  • sed "$d" — says to remove the last line ( its now reversed). The last line is just a period which including would make the call delete everything in the directory (and subs!)

, , ,

30
Apr
private double[] getGPS() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
        List<String> providers = lm.getProviders(true);

        /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
        Location l = null;
       
        for (int i=providers.size()-1; i>=0; i--) {
                l = lm.getLastKnownLocation(providers.get(i));
                if (l != null) break;
        }
       
        double[] gps = new double[2];
        if (l != null) {
                gps[0] = l.getLatitude();
                gps[1] = l.getLongitude();
        }
        return gps;
}

30
Apr

Set the flag FLAG_KEEP_SCREEN_ON for your Activity. You can also use XML attribute android:keepScreenOn for different views.

//First method: TestActivity.java
public class TestActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UtilSystem.setKeepScreenOn(this, true);
  }

 
  public void setKeepScreenOn(Activity activity, boolean keepScreenOn) {
    if(keepScreenOn) {
      activity.getWindow().
        addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    } else {
      activity.getWindow().
        clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
  }
}

// Second method: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android = "http://schemas.android.com/apk/res/android"
  android:keepScreenOn = "true"
  android:orientation = "vertical"
  android:layout_width = "fill_parent"
  android:layout_height = "fill_parent">
  <!-- ... -->
</LinearLayout>

16
Apr

The Android way of delegating actions to other applications is to invoke an Intent  that describes what you want done. This process involves three pieces: The Intent itself, a call to start the external Activity, and some code to handle the image data when focus returns to your activity.

Here’s a function that invokes an intent to capture a photo.

private void dispatchTakePictureIntent(int actionCode) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(takePictureIntent, actionCode);
}

With this code, your application gains the ability to make another camera application take photos. Make sure that there is a compatible application ready to catch the Intent.

Function to check whether an app can handle your intent:

public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

,

13
Apr

Intents are just what they sound like, a way to declare to the Android Framework what you intend to do. This can be starting a specific activity, or it can be just asking Android to find some program that can perform an action (whether or not you know what programs are available). We can also go in the other direction, and determine what actions are available to us for a particular piece of content. We are going to cover each of these topics in this article.

Here is the basic ListActivity example.

package com.learnandroid.intents;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class UsingIntentsActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListAdapter adapter = createAdapter();
        setListAdapter(adapter);
    }

    protected ListAdapter createAdapter()
    {
    	String[ ] listValues = new String[ ] {
    			"The Activity You Know",
    			"The URI You Know",
    			"When You Just Don't Know"
    	};

    	// Create a simple array adapter (of type string) with the test values
    	ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1
    			, listValues);

    	return adapter;
    }
}

09
Apr

Adapters in Android

An adapter is how Android translates data from some data source onto a view. Typically adapters are used on ListViews and GridViews, and Android provides some very helpful adapters out of the box.

The adapter goes hand-in-hand with a corresponding view (which in our case is a ListView.) Together they bring cleaner code, optimized performance, and reusability to your project.

Cleaner separation of concerns

When you add an object to an adapter, the action also adds the representative view for that object to any lists bound to the adapter. Your code that is adding data into the list through the adapter doesn’t have to know how the list is built for each item. Likewise, the code that knows how to build views for each item in your list doesn’t have to know where the data is coming from.

This makes a somewhat clean separation of concerns that normally overlap in one spot. Those of you who have written many lines of code to populate UI elements with varied data can understand how tangled the project becomes when the code retrieving data is also the code rendering it.

Optimizations: View Recycling

Another great benefit of using a ListView/adapter is the immense performance gains it can bring. If you’ve ever built a ScrollView with a list of child views, you’ll notice that performance becomes slow quickly. The ListView/adapter pair solves this with a traditional technique: view recycling.

View recycling is a technique in which view objects are re-used once their current locations are no longer visible. This has a great performance advantage– as your list of items grows, the total number of views remains the same, which corresponds to the distinct number of views drawn in a single screenful. Even better yet, the process is handled behind the scenes, so your adapter should only be aware that views are reused, not necessarily how they are reused.

Code Reusability

Finally the code you write for an adapter, and the separation it forces in the data, view, and adaptation concerns, will result in your code being much more reusable. Where you may have previously written all of the code directly into some Activity for displaying a list of complex objects, now you have a separate class that you can reuse for other lists. In fact, you can even vary the layout the adapter uses without changing anything about the adapter itself.

06
Apr

Sqlite is the ubiquitous database for mobile applications on iPad, iPhone and Android. It is also used by certain internet browsers, web application frameworks and software products for their local storage needs. While doing penetration tests, we often see sensitive information like usernames, passwords, account numbers, SSN etc  insecurely stored in these databases. Thus, every penetration test requires comprehensive analysis of the local databases being used.

While analyzing databases, a penetration tester repeatedly does the following:

  • Opens the database in sqlite reader (sqlite3 or other readers)
  • Views various tables and columns to understand database layout and schema.
  • Analyzes the storage for sensitive information.

As the number and size of database increases, the analysis time increases exponentially. To escape the recurring pain, the following ruby script helps. The script achieves the following:

  • Analyzes multiple databases in a single run.
  • Queries and displays database schema.
  • Provides an option to run search on Table and Column Names for quick analysis.
  • Performs case-insensitive regular expression search (default).
  • Displays Database, Tables and Row Number reference for every successful match.
  • Dumps database rows on a successful match.
  • Looks for search strings in the following:
    • Table Name
    • Column Names
    • Actual Data

 

Sqlitespy Code:

require 'rubygems'

require 'optparse'

require 'ostruct'

require 'sequel'

class CmdLineOptions

def self.parse(args)

options = OpenStruct.new

options.dbs = []

options.sstrings = []

options.show_schema = false

options.case_sensitive = false

options.exact = false

options.verbose = false

options.rowdump = false

options.metadata = false

opts = OptionParser.new do |opts|

opts.banner = "Usage: sqlitespy.rb [options]\n\nSpecific Options:"

opts.on("-d", "--database DATABASE_PATH",

"Sqlite database to analyze.") do |db|

options.dbs << db

end

opts.on("-s", "--show-schema", "Show database schema") do |show|

options.show_schema = show;

end

opts.on("--find x,y,z", Array, "Strings to search") do |list|

options.sstrings = list

end

opts.on("-c", "--case-sensitive", "Perform case sensitive search. Default is case insensitive.") do |case_sensitive|

options.case_sensitive = case_sensitive;

end

opts.on("-e", "--exact--match", "Perform exact match for the search strings") do |v|

options.exact = v;

end

opts.on("-r", "--row-dump", "Dump Database Row when a match is found") do |v|

options.rowdump = v;

end

opts.on("-m", "--metadata", "Look for search strings only in DB metadata (table and column names)") do |v|

options.metadata = v;

end

opts.on("-v", "--verbose", "Verbose output") do |v|

options.verbose = v;

end

opts.on_tail("-h", "--help", "Show this message") do

puts opts

exit

end

end

opts.parse!(args)

options

end# parse()

end# class CmdLineOptions

options = nil

begin

options = CmdLineOptions.parse(ARGV)

rescue (OptionParser::InvalidOption)

$stderr.puts "[-] Invalid option "

options = CmdLineOptions.parse(ARGV+["-h"])

end

if(options.dbs.length == 0)

$stderr.puts "[-] No Database available. Exiting !!"

exit

end

dbs = []

options.dbs.uniq!

dbs = options.dbs.collect do |db|

begin

throw Errno::ENOENT unless(File.file?(db))

Sequel.sqlite(db).tables

db

rescue

$stderr.puts "[-] \"#{db}\" is not a sqlite database"

nil

end

end

options.dbs = dbs.compact

if(options.dbs.length == 0)

$stderr.puts "[-] No Database available. Exiting."

exit

end

options.sstrings.uniq!

if(options.show_schema)

puts

puts "+"*80

puts "Database Schemas"

puts "+"*80

options.dbs.each do |db|

puts

puts "[DATABASE] #{db}"

Sequel.sqlite(db) do |dbhandle|

dbhandle.tables.each do |table|

puts "\t[TABLE] #{table}"

puts "\t\t[COLUMNS] #{dbhandle[table.to_sym].columns.join(', ')}"

end

end

end

puts "-"*80

end

regex_strings = []

regex_strings = options.sstrings.collect do |search|

regexstr = ""

regex = nil

if(options.exact)

regexstr = "^#{search}$"

else

regexstr = "#{search}"

end

if(options.case_sensitive)

regex = Regexp.new("#{regexstr}")

else

regex = Regexp.new("#{regexstr}", Regexp::IGNORECASE)

end

regex

end

 

options.sstrings = regex_strings

options.dbs.each do |database|

if(options.verbose)

puts

puts "+"*80

puts "Analyzing Database '#{database}'"

puts "+"*80

end

Sequel.sqlite(database) do |databasehandle|

databasehandle.tables.each do |table|

if(options.verbose)

puts

puts "-"*80

puts "Analyzing Table '#{table}'"

puts "-"*80

end

options.sstrings.each do |regex|

if(regex.match(table.to_s))

puts "[+] Table Name Match Found -> Database '#{database}' -> TABLE '#{table}'"

end

end

#Column Name Search

databasehandle[table.to_sym].columns.each do |column_name|

options.sstrings.each do |regex|

if(regex.match(column_name.to_s))

puts "[+] Column Name Match Found -> Database '#{database}' -> TABLE '#{table}' -> COLUMN '#{column_name}'"

end

end

end

#Data Search

if(options.sstrings.length > 0 && !options.metadata)

row = 0

databasehandle[table].each do |rowHash|

row = row + 1

rowHash.each do |key, value|

options.sstrings.each do |regex|

if(regex.match(value.to_s))

puts "[+] Data Match Found -> Database '#{database}' -> TABLE '#{table}', COLUMN '#{key}' -> ROW '#{row}'"

puts "\t[*] Row Dump\t=>\t#{rowHash.values.join('|')}" if(options.rowdump)

end

end

end

end

end

end

end

end

, , , ,