Sunday, September 19, 2010

hi

test

Custom MultiColumn Listview with Image thumbnail

public static ArrayList vidID = new ArrayList();
public static Hashtable> VideoTable = new Hashtable>();
Hashtable _tempVideo = new Hashtable();
ArrayList db_id;


--Start any required Loop

_tempVideo.put("id", curValue);
_tempVideo.put("title", curValue);
_tempVideo.put("filename", curValue);
_tempVideo.put("thumbnail", curValue);

VideoTable.put(curVidId, _tempVideo);
vidID.add(curVidId);

_tempVideo = new Hashtable();

---End Loop

private void fillData() {

ListView list = (ListView) findViewById(R.id.ListView01);

ArrayList> mylist = new ArrayList>();
HashMap map;

db_id = new ArrayList();
for (int i = 0; i < vidID.size(); i++) {
Hashtable temp = VideoTable
.get(vidID.get(i));
try {
map = new HashMap();
map.put("id", temp.get("id"));
map.put("title", temp.get("title"));
map.put("description", temp.get("description"));
map.put("theartist", temp.get("theartist"));
map.put("duration", temp.get("duration"));
map.put("views", temp.get("views") + " views");
map.put("server", temp.get("server"));
map.put("filename", temp.get("filename"));
map.put("thumbnail", temp.get("thumbnail"));

mylist.add(map);
db_id.add(vidID.get(i));
} catch (Exception e) {
}
}
SimpleAdapter videolist = new SimpleAdapter(this, mylist,
R.layout.videorow, new String[] { "id", "title", "views",
"duration", "description", "server", "filename",
"thumbnail"}, new int[] { R.id.TextView05,
R.id.TextView01, R.id.TextView02, R.id.TextView03,
R.id.TextView04, R.id.TextView06, R.id.TextView07,
R.id.TextView08 });
list.setAdapter(videolist);
list.setOnItemClickListener(this);
list.setTextFilterEnabled(true);
list.setOnHierarchyChangeListener(this);
}

@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {

TextView filename = (TextView) arg1.findViewById(R.id.TextView07);
String url = filename.getText().toString();
Log.e(".", url);
Bundle bundle = new Bundle();
bundle.putString("URL", url);
Intent myIntent = new Intent();
myIntent.setClassName("Package Name", "Package Name With Class");
myIntent.putExtras(bundle);
startActivity(myIntent);
}


@Override
public void onChildViewAdded(View parent, View child) {
View row = child;
try {
ImageView imView = (ImageView) row.findViewById(R.id.ImageView01);
imView.setImageBitmap(null);
TextView id = (TextView) row.findViewById(R.id.TextView05);
TextView thumbnail = (TextView) row.findViewById(R.id.TextView08);
TextView filename = (TextView) row.findViewById(R.id.TextView07);
imView.setTag(filename.getText().toString());
String imgurl = thumbnail.getText().toString();
grabURL(imgurl, imView, filename.getText().toString());

ImageView addFav = (ImageView) row.findViewById(R.id.ImageView02);
addFav.setTag(id.getText().toString());
addFav.setOnClickListener(myListner);
} catch (Exception e) {
}
}
@Override
public void onChildViewRemoved(View parent, View child) {

try {
View row = child;
ImageView imView = (ImageView) row.findViewById(R.id.ImageView02);
imView.setTag(null);
imView.setImageBitmap(null);
} catch (Exception e) {
}
}


public void grabURL(String url, ImageView iv, String name) {
GrabURL a = new GrabURL();
a.imgView1 = iv;
a.name = name;
a.execute(url);
}

private class GrabURL extends AsyncTask {
ImageView imgView1;
String name;

protected void onPreExecute() {
}

protected Bitmap doInBackground(String... urls) {
URL myFileUrl = null;
Bitmap bmImg = null;
try {
myFileUrl = new URL(urls[0]);
} catch (MalformedURLException e) {
}

try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);

} catch (Exception e) {
Log.e(".", e.getMessage());
}
return bmImg;
}

protected void onPostExecute(Bitmap bm) {
if (name == imgView1.getTag().toString())
imgView1.setImageBitmap(bm);
}

}

Sunday, September 5, 2010

Securing Android LVL Applications

Securing Android LVL Applications: "

[This post is by Trevor Johns, who's a Developer Programs Engineer working on Android. — Tim Bray]

The Android Market licensing service is a powerful tool for protecting your applications against unauthorized use. The License Verification Library (LVL) is a key component. A determined attacker who’s willing to disassemble and reassemble code can eventually hack around the service; but application developers can make the hackers’ task immensely more difficult, to the point where it may simply not be worth their time.

Out of the box, the LVL protects against casual piracy; users who try to copy APKs directly from one device to another without purchasing the application. Here are some techniques to make things hard, even for technically skilled attackers who attempt to decompile your application and remove or disable LVL-related code.

  • You can obfuscate your application to make it difficult to reverse-engineer.

  • You can modify the licensing library itself to make it difficult to apply common cracking techniques.

  • You can make your application tamper-resistant.

  • You can offload license validation to a trusted server.

This can and should be done differently by each app developer. A guiding principle in the design of the licensing service is that attackers must be forced to crack each application individually, and unfortunately no client-side code can be made 100% secure. As a result, we depend on developers introducing additional complexity and heterogeneity into the license check code — something which requires human ingenuity and and a detailed knowledge of the application the license library is being integrated into.

Technique: Code Obfuscation

The first line of defense in your application should be code obfuscation. Code obfuscation will not protect against automated attacks, and it doesn’t alter the flow of your program. However, it does make it more difficult for attackers to write the initial attack for an application, by removing symbols that would quickly reveal the original structure of a compiled application. As such, we strongly recommend using code obfuscation in all LVL installations.

To understand what an obfuscator does, consider the build process for your application: Your application is compiled and converted into .dex files and packaged in an APK for distribution on devices. The bytecode contains references to the original code — packages, classes, methods, and fields all retain their original (human readable) names in the compiled code. Attackers use this information to help reverse-engineer your program, and ultimately disable the license check.

Obfuscators replace these names with short, machine generated alternatives. Rather than seeing a call to dontAllow(), an attacker would see a call to a(). This makes it more difficult to intuit the purpose of these functions without access to the original source code.

There are a number of commercial and open-source obfuscators available for Java that will work with Android. We have had good experience with ProGuard, but we encourage you to explore a range of obfuscators to find the solution that works best for you.

We will be publishing a separate article soon that provides detailed advice on working with ProGuard. Until then, please refer to the ProGuard documentation.

Technique: Modifying the license library

The second line of defense against attack from crackers is to modify the license verification library in such a way that it’s difficult for an attacker to modify the disassembled code and get a positive license check as result.

This actually provides protection against two different types of attack: it protects against attackers trying to crack your application, but it also prevents attacks designed to target other applications (or even the stock LVL distribution itself) from being easily ported over to your application. The goal should be to both increase the complexity of your application’s bytecode and make your application’s LVL implementation unique.

When modifying the license library, there are three areas that you will want to focus on:

  • The core licensing library logic.

  • The entry/exit points of the licensing library.

  • How your application invokes the licensing library and handles the license response.

In the case of the core licensing library, you’ll primarily want to focus on two classes which comprise the core of the LVL logic: LicenseChecker and LicenseValidator.

Quite simply, your goal is to modify these two classes as much as possible, in any way possible, while still retaining the original function of the application. Here are some ideas to get you started, but you’re encouraged to be creative:

  • Replace switch statements with if statements.

  • Use XOR or hash functions to derive new values for any constants used and check for those instead.

  • Remove unused code. For instance, if you’re sure you won’t need swappable policies, remove the Policy interface and implement the policy verification inline with the rest of LicenseValidator.

  • Move the entirety of the LVL into your own application’s package.

  • Spawn additional threads to handle different parts of license validation.

  • Replace functions with inline code where possible.

For example, consider the following function from LicenseValidator:

public void verify(PublicKey publicKey, int responseCode, String signedData, String signature) {
// ... Response validation code omitted for brevity ...
switch (responseCode) {
// In Java bytecode, LICENSED will be converted to the constant 0x0
case LICENSED:
case LICENSED_OLD_KEY:
LicenseResponse limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
handleResponse(limiterResponse, data);
break;
// NOT_LICENSED will be converted to the constant 0x1
case NOT_LICENSED:
handleResponse(LicenseResponse.NOT_LICENSED, data);
break;
// ... Extra response codes also removed for brevity ...
}

In this example, an attacker might try to swap the code belonging to the LICENSED and NOT_LICENSED cases, so that an unlicensed user will be treated as licensed. The integer values for LICENSED (0x0) and NOT_LICENSED (0x1) will be known to an attacker by studying the LVL source, so even obfuscation makes it very easy to locate where this check is performed in your application’s bytecode.

To make this more difficult, consider the following modification:

public void verify(PublicKey publicKey, int responseCode, String signedData, String signature) {
// ... Response validation code omitted for brevity …

// Compute a derivative version of the response code
// Ideally, this should be placed as far from the responseCode switch as possible,
// to prevent attackers from noticing the call to the CRC32 library, which would be
// a strong hint as to what we're done here. If you can add additional transformations
// elsewhere in before this value is used, that's even better.
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
crc32.update(responseCode);
int transformedResponseCode = crc32.getValue();

// ... put unrelated application code here ...
// crc32(LICENSED) == 3523407757
if (transformedResponse == 3523407757) {
LicenseResponse limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
handleResponse(limiterResponse, data);
}
// ... put unrelated application code here ...
// crc32(LICENSED_OLD_KEY) == 1007455905
if (transformedResponseCode == 1007455905) {
LicenseResponse limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
handleResponse(limiterResponse, data);
}
// ... put unrelated application code here ...
// crc32(NOT_LICENSED) == 2768625435
if (transformedResponseCode == 2768625435):
userIsntLicensed();
}
}

In this example, we’ve added additional code to transform the license response code into a different value. We’ve also removed the switch block, allowing us to inject unrelated application code between the three license response checks. (Remember: The goal is to make your application’s LVL implementation unique. Do not copy the code above verbatim — come up with your own approach.)

For the entry/exit points, be aware that attackers may try to write a counterfeit version of the LVL that implements the same public interface, then try to swap out the relevant classes in your application. To prevent this, consider adding additional arguments to the LicenseChecker constructor, as well as allow() and dontAllow() in the LicenseCheckerCallback. For example, you could pass in a nonce (a unique value) to LicenseChecker that must also be present when calling allow().

Note: Renaming allow() and dontAllow() won’t make a difference, assuming that you’re using an obfuscator. The obfuscator will automatically rename these functions for you.

Be aware that attackers might try and attack the calls in your application to the LVL. For example, if you display a dialogue on license failure with an “Exit” button, consider what would happen if an attacker were to comment out the line of code that displayed that window. If the user never pushes the “Exit” button in the dialog (which is no not being displayed) will your application still terminate? To prevent this, consider invoking a different Activity to handle informing a user that their license is invalid, and immediately terminating the original Activity; add additional finish() statements to other parts of your code that get will get executed in case the original one gets disabled; or set a timer that will cause your application to be terminated after a timeout. It’s also a good idea to defer the license check until your application has been running a few minutes, since attackers will be expecting the license check to occur during your application’s launch.

Finally, be aware that certain methods cannot be obfuscated, even when using a tool such as ProGuard. As a key example, onCreate() cannot be renamed, since it needs to remain callable by the Android system. Avoid putting license check code in these methods, since attackers will be looking for the LVL there.

Technique: Make your application tamper-resistant

In order for an attacker to remove the LVL from your code, they have to modify your code. Unless done precisely, this can be detected by your code. There are a few approaches you can use here.

The most obvious mechanism is to use a lightweight hash function, such as CRC32, and build a hash of your application’s code. You can then compare this checksum with a known good value. You can find the path of your application’s files by calling context.GetApplicationInfo() — just be sure not to compute a checksum of the file that contains your checksum! (Consider storing this information on a third-party server.)

[In a late edit, we removed a suggestion that you use a check that relies on GetInstallerPackageName when our of our senior engineers pointed out that this is undocumented, unsupported, and only happens to work by accident. –Tim]

Also, you can check to see if your application is debuggable. If your application tries to keep itself from performing normally if the debug flag is set, it may be harder for an attacker to compromise:

boolean isDebuggable =  ( 0 != ( getApplcationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE ) );

Technique: Offload license validation to a trusted server

If your application has an online component, a very powerful technique to prevent piracy is to send a copy of the license server response, contained inside the ResponseData class, along with its signature, to your online server. Your server can then verify that the user is licensed, and if not refuse to serve any online content.

Since the license response is cryptographically signed, your server can check to make sure that the license response hasn’t been tampered with by using the public RSA key stored in the Android Market publisher console.

When performing the server-side validation, you will want to check all of the following:

  • That the response signature is valid.

  • That the license service returned a LICENSED response.

  • That the package name and version code match the correct application.

  • That the license response has not expired (check the VT license response extra).

  • You should also log the userId field to ensure that a cracked application isn’t replaying a license response from another licensed user. (This would be visible by an abnormally high number of license checks coming from a single userId.)

To see how to properly verify a license response, look at LicenseValidator.verify().

As long as the license check is entirely handled within server-code (and your server itself is secure), it’s worth nothing that even an expert cracker cannot circumvent this mechanism. This is because your server is a trusted computing environment.

Remember that any code running on a computer under the user’s control (including their Android device) is untrusted. If you choose to inform the user that the server-side license validation has failed, this must only be done in an advisory capacity. You must still make sure that your server refuses to serve any content to an unlicensed user.

Conclusion

In summary, remember that your goal as an application developer is to make your application’s LVL implementation unique, difficult to trace when decompiled, and resistant to any changes that might be introduced. Realize that this might involve modifying your code in ways that seem counter-intuitive from a traditional software engineering viewpoint, such as removing functions and hiding license check routines inside unrelated code.

For added protection, consider moving the license check to a trusted server, where attackers will be unable to modify the license check code. While it’s impossible to write 100% secure validation code on client devices, this is attainable on a machine under your control.

And above all else, be creative. You have the advantage in that you have access to a fully annotated copy of your source code — attackers will be working with uncommented bytecode. Use this to your advantage.

Remember that, assuming you’ve followed the guidelines here, attackers will need to crack each new version of your application. Add new features and release often, and consider modifying your LVL implementation with each release to create additional work for attackers.

And above all else, listen to your users and keep them happy. The best defense against piracy isn’t technical, it’s emotional.



"

Wednesday, September 1, 2010

Maintaining global Application state

Maintaining global Application state: "




SDK Version: 

M3






0



As a possible solutions mentioned in previous article Leaving an Android application the Application object can come handy. If you want to store data, global variables that needs to be accessed from everywhere in the application, from multiple Activities, in other words is you want to maintain a global 'state' of the whole application the Application object can help.


For this we must make a class which extends the Android.app.Application class add our own methods to it, and define this class in the AndroidManifest.xml as below:



  1. An example for the Application class:

  2.  

  3. public class HelloApplication extends Application {

  4.         private int globalVariable=1;

  5.  

  6.         public int getGlobalVariable() {

  7.                 return globalVariable;

  8.         }


read more

"

Rockbox For Android Now Semi-Functional

Rockbox For Android Now Semi-Functional: "

image


The popular, open-source media player firmware Rockbox has recently been made available for Android. Rather than run as an operating system, Rockbox operates as a standalone application that you can install as usual with an APK. Development is still on-going, but Rockbox dev kugel has a few pre-compiled APKs hosted for you to try out if you’re interested.


image


Download:


240 x 320     320 x 480     480 x 800 


These builds are unofficial and are purely for demonstrative purposes, but they seem to work pretty nicely. Currently the navigation/control interaction method is touchscreen...

"

Official Pictures Of The T-Mobile G2 Leaked, Take A Look At That Glorious Keyboard

Official Pictures Of The T-Mobile G2 Leaked, Take A Look At That Glorious Keyboard: "

g2 1


In case you’re one of many people eagerly awaiting the successor of the original Android phone, you may be excited to hear that CellPhoneSignal has some high-quality (albeit quite small), official pictures of the upcoming T-Mobile G2, which show off just how nice that keyboard looks (not to mention how good vanilla FroYo looks, too).


g2 1 g2 2 g2 3


So, what do you think? Is this first HSPA+ compatible handset not enough for you to leave your Vibrant? Keyboard not good enough to leave your trusty old G1? Planning on buying one on launch day? Tell us in the...

"

Twitter Changes Login System, Catches HTC Off Guard (Despite An 8 Month Heads-Up)

Twitter Changes Login System, Catches HTC Off Guard (Despite An 8 Month Heads-Up): "

peep


Well, this is somewhat entertaining (probably because I don’t use Peep – those of you who do probably find it a lot less funny). Twitter flipped the switch on an application login change on Monday, and as a result users can’t login to Twitter through HTC Peep. It’s a bit difficult to understand without going into more detail, so without further ado, more detail.


Previously, applications could use one of two ways to login to Twitter: Basic Authentication and OAuth. The Twitter devs say it quite nicely, so I’ll just do less work and quote them:


In

...

"

Sunday, August 22, 2010

How to Send Email in Android ?

Intent sendIntent;

sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT,
"Test");
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hy Testing");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"
+ file.getAbsolutePath()));
sendIntent.setType("image/jpeg");
startActivity(Intent.createChooser(sendIntent, "Send Mail"));

AsyncTask background Process / Thread in android

private class AsyncCheckInternet extends AsyncTask {
@Override
protected void onPreExecute() {
dialogProcess = ProgressDialog.show(classname.this, "",
"processing...", true);
}
@Override
protected Boolean doInBackground(Void... voids) {

// Background function logic
}
@Override
protected void onPostExecute(Boolean params) {
dialogProcess.dismiss();
// After background Process end Called params true or false....
}
}
}


// call background AsyncTask

new AsyncCheckInternet().execute();

How to use GestureDetector in Android application ?

// Gesture Detect
private static final int SWIPE_MIN_DISTANCE = 30;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 50;

private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

img1 = (ImageView) findViewById(R.id.ImageView01);
img2 = (ImageView) findViewById(R.id.ImageView02);
img3 = (ImageView) findViewById(R.id.ImageView03);
img4 = (ImageView) findViewById(R.id.ImageView04);

rel1 = (RelativeLayout) findViewById(R.id.RelativeLayout01);
rel2 = (RelativeLayout) findViewById(R.id.RelativeLayout05);
rel3 = (RelativeLayout) findViewById(R.id.RelativeLayout06);
rel4 = (RelativeLayout) findViewById(R.id.RelativeLayout07);



gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};

rel1.setOnTouchListener(gestureListener);
rel2.setOnTouchListener(gestureListener);
rel3.setOnTouchListener(gestureListener);
rel4.setOnTouchListener(gestureListener);

img1.setOnTouchListener(gestureListener);
img2.setOnTouchListener(gestureListener);
img3.setOnTouchListener(gestureListener);
img4.setOnTouchListener(gestureListener);


class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe

if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY
&& curPage < _totPages - 1) {

//// Logic
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY
&& curPage > 0) {
//// Logic
}

} catch (Exception e) {
// nothing
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
// TODO Auto-generated method stub
return super.onScroll(e1, e2, distanceX, distanceY);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}

Wednesday, July 21, 2010

How to Connect Face Book in Android ?

http://code.google.com/p/fbconnect-android/source/browse/sample/src/com/codecarpet/fbconnect/sample/MainActivity.java


http://www.mobisoftinfotech.com/blog/android/845/


These links are useful to connect facebook in android.

Monday, July 19, 2010

Android – Listen for incoming SMS messages

public class SMSApp extends IntentReceiver {
private static final String LOG_TAG = "SMSApp";

/* package */ static final String ACTION =
"android.provider.Telephony.SMS_RECEIVED";

public void onReceiveIntent(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)) {
StringBuilder buf = new StringBuilder();
Bundle bundle = intent.getExtras();

if (bundle != null) {
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (int i = 0; i < messages.length; i++) {
SmsMessage message = messages[i];
buf.append("Received SMS from ");
buf.append(message.getDisplayOriginatingAddress());
buf.append(" - ");
buf.append(message.getDisplayMessageBody());
}
}
Log.i(LOG_TAG, "[SMSApp] onReceiveIntent: " + buf);
NotificationManager nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);

nm.notifyWithText(123, buf.toString(),
NotificationManager.LENGTH_LONG, null);

}
}

private void appendData(StringBuilder buf, String key, String value) {
buf.append(", ");
buf.append(key);
buf.append('=');
buf.append(value);
}
}

SMS notifications in Android

SMSNotify.java
================

public class SMSNotify extends Activity {

public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(R.string.app_name); // cancel notification
}
}
================================================
public class SMSNotifyExample extends IntentReceiver {
/** TAG used for Debug-Logging */
private static final String LOG_TAG = “SMSReceiver”;
// public static final int LENGTH_LONG = 10;
/* A Random IDs used for the Notification */
public static final int NOTIFICATION_ID_RECEIVED = 0×1221;

/** The Action fired by the Android-System when a SMS was received.
* We are using the Default Package-Visibility */
static final String ACTION = “android.provider.Telephony.SMS_RECEIVED”;
private CharSequence from = null;
private CharSequence tickerMessage = null;
public void onReceiveIntent(Context context, Intent intent) {

NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (intent.getAction().equals(ACTION)) {
// if(message starts with SMStretcher recognize BYTE)
StringBuilder sb = new StringBuilder();

Bundle bundle = intent.getExtras();
if (bundle != null) {
/* Get all messages contained in the Intent*/
SmsMessage[] messages =
Telephony.Sms.Intents.getMessagesFromIntent(intent);

/* Feed the StringBuilder with all Messages found. */
for (SmsMessage currentMessage : messages){
sb.append(“Received compressed SMS\nFrom: “);
/* Sender-Number */
sb.append(currentMessage.getDisplayOriginatingAddress());
// set
from = currentMessage.getDisplayOriginatingAddress();
sb.append(“\n—-Message—-\n”);
/* Actual Message-Content */
sb.append(currentMessage.getDisplayMessageBody());
}
}
/* Logger Debug-Output */
Log.i(LOG_TAG, “[SMSApp] onReceiveIntent: ” + sb);

this.abortBroadcast();
/* Start the Main-Activity */
Intent i = new Intent(context, SMSNotifyActivity.class);
i.setLaunchFlags(Intent.NEW_TASK_LAUNCH);
context.startActivity(i);

// CharSequence from = currentMessage.getDisplayOriginatingAddress();
CharSequence appName = “SMSNotifyExample”;
tickerMessage = sb.toString();
Long theWhen = System.currentTimeMillis();

Intent appIntent = new Intent(Intent.VIEW_ACTION, Sms.Inbox.CONTENT_URI);

Notification notif = new Notification(
context, // our context
R.drawable.incoming, // the icon for the status bar
tickerMessage, // the text to display in the ticker
theWhen, // the timestamp for the notification
from, // the title for the notification
tickerMessage, // the details to display in the notification
i, // the contentIntent (see above)
R.drawable.chat, // the app icon
appName, // the name of the app
appIntent); // intent that shows the inbox when you click on icon

notif.vibrate = new long[] { 100, 250, 100, 500};

nm.notify(R.string.alert_message, notif);

}
}
}
AndroidManifest.xml
=====================




How do you format date and time in Android?

Date date = new Date(location.getTime());
DateFormat dateFormat = DateFormat.getDateTimeInstance();
mTimeText.setText("Time: " + dateFormat.format(date));

How to get date, month, year values from the current date JAVA ?

import java.util.Calendar;

public class CalendarExample
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
int dow = cal.get(Calendar.DAY_OF_WEEK);
int dom = cal.get(Calendar.DAY_OF_MONTH);
int doy = cal.get(Calendar.DAY_OF_YEAR);
}
}

Tuesday, July 13, 2010

Important Links

Video ---> http://davanum.wordpress.com/2009/12/04/android-%E2%80%93-videomusic-player-sample-take-2/

Call Telephony Manager ----http://www.google.com/codesearch/p?hl=en#zvQ8rp58BUs/trunk/phone/src/i4nc4mp/myLock/phone/CallPrompt.java&q=itelephony package:http://mylockforandroid\.googlecode\.com&d=0


http://code.google.com/p/teddsdroidtools/source/browse/#svn/trunk/teddsdroidtools/src/tss/droidtools/phone

Android Widget Example Links

http://www.helloandroid.com/tutorials/days-xmas-widget-tutorial

Wednesday, July 7, 2010

How to fetch Contacts List name and number in android?

//=================main.java=========================

private static final int PICK_CONTACT_REQUEST = 1;

private final ContactAccessor mContactAccessor = ContactAccessor
.getInstance();
Boolean select;

// any click event
public void onClick(View v) {
select = true;
pickContact();
}

protected void pickContact() {
startActivityForResult(mContactAccessor.getPickContactIntent(),
PICK_CONTACT_REQUEST);

}


private void loadContactInfo(Uri contactUri) {

AsyncTask task = new AsyncTask() {

@Override
protected ContactInfo doInBackground(Uri... uris) {
return mContactAccessor.loadContact(getContentResolver(),
uris[0]);
}

@Override
protected void onPostExecute(ContactInfo result) {
bindView(result);
}
};

task.execute(contactUri);
}

protected void bindView(ContactInfo contactInfo) {
if (select == true)
{
EditText Name = (EditText) findViewById(R.id.EditText01);
Name.setText(contactInfo.getDisplayName());

EditText Number = (EditText) findViewById(R.id.EditText02);
Number.setText(contactInfo.getPhoneNumber());
}

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CONTACT_REQUEST && resultCode == RESULT_OK) {
loadContactInfo(data.getData());
}
}


//=====================ContactAccessor.java===============
public abstract class ContactAccessor {

private static ContactAccessor sInstance;

public static ContactAccessor getInstance() {
if (sInstance == null) {
String className;

int sdkVersion = Integer.parseInt(Build.VERSION.SDK); // Cupcake
// style

if (sdkVersion < Build.VERSION_CODES.ECLAIR) { className = "android.contacts.ContactAccessorSdk3_4"; } else { className = "android.contacts.ContactAccessorSdk5"; } try { Class clazz = Class.forName(
className).asSubclass(ContactAccessor.class);
sInstance = clazz.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}

return sInstance;
}

public abstract Intent getPickContactIntent();

public abstract ContactInfo loadContact(ContentResolver contentResolver,
Uri contactUri);
}

//=======================ContactAccessorSdk3_4.java==================
public class ContactAccessorSdk3_4 extends ContactAccessor {

/**
* Returns a Pick Contact intent using the pre-Eclair "people" URI.
*/
@Override
public Intent getPickContactIntent() {
return new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
}

/**
* Retrieves the contact information.
*/
@Override
public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) {
ContactInfo contactInfo = new ContactInfo();
Cursor cursor = contentResolver.query(contactUri,
new String[]{People.DISPLAY_NAME}, null, null, null);
try {
if (cursor.moveToFirst()) {
contactInfo.setDisplayName(cursor.getString(0));
}
} finally {
cursor.close();
}

Uri phoneUri = Uri.withAppendedPath(contactUri, Phones.CONTENT_DIRECTORY);
cursor = contentResolver.query(phoneUri,
new String[]{Phones.NUMBER}, null, null, Phones.ISPRIMARY + " DESC");

try {
if (cursor.moveToFirst()) {
contactInfo.setPhoneNumber(cursor.getString(0));
}
} finally {
cursor.close();
}

return contactInfo;
}
}

//========================ContactAccessorSdk5.java==============================
public class ContactAccessorSdk5 extends ContactAccessor {

/**
* Returns a Pick Contact intent using the Eclair "contacts" URI.
*/
@Override
public Intent getPickContactIntent() {
return new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
}

/**
* Retrieves the contact information.
*/
@Override
public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) {
ContactInfo contactInfo = new ContactInfo();
long contactId = -1;

// Load the display name for the specified person
Cursor cursor = contentResolver.query(contactUri,
new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null);
try {
if (cursor.moveToFirst()) {
contactId = cursor.getLong(0);
contactInfo.setDisplayName(cursor.getString(1));
}
} finally {
cursor.close();
}

// Load the phone number (if any).
cursor = contentResolver.query(Phone.CONTENT_URI,
new String[]{Phone.NUMBER},
Phone.CONTACT_ID + "=" + contactId, null, Phone.IS_SUPER_PRIMARY + " DESC");
try {
if (cursor.moveToFirst()) {
contactInfo.setPhoneNumber(cursor.getString(0));
}
} finally {
cursor.close();
}

return contactInfo;
}
}
//======================ContactInfo.java===============================
public class ContactInfo {

private String mDisplayName;
private String mPhoneNumber;

public void setDisplayName(String displayName) {
this.mDisplayName = displayName;
}

public String getDisplayName() {
return mDisplayName;
}

public void setPhoneNumber(String phoneNumber) {
this.mPhoneNumber = phoneNumber;
}

public String getPhoneNumber() {
return mPhoneNumber;
}
}

Friday, July 2, 2010

Using Process Dialog Box in Android

rogressDialog dialog;
dialog = ProgressDialog.show(classname.this, "","Downloading ............", true);
dialog.dismiss();

Android + Google Checkout = Just as good as cash?

Android + Google Checkout = Just as good as cash?: "

As the world inches closer to switching from a cash society to an all-digital payment society, companies are finding new ways to let users exchange money. PayPal bumps transactions between iPhones, Square can process credit card transactions on a Nexus One, and now Google is offering Google Checkout support between Android and Chrome.

The Android Payment Extension is designed to help merchants accept debit and credit card purchases when someone doesn’t have cash available. Street vendors, weekend garage sale folks, or just two people in a coffee house looking to perform a transaction can now use Google Checkout and some QR codes to accomplish the task. Here’s how Google describes the process:

1. Create a Google Checkout merchant account and configure your tax on the Settings Tab

2. Use the Google Checkout Store Gadget Wizard to generate a webstore template

3. Fill in the Google Spreadsheet with information about the items you wish to sell

4. Create a Google Sites page and follow the wizard to embed the Store Gadget

5. Install the Android Payment Chrome Extension

Afterwards, the customer scans a QR code, logs into his/her Checkout account, and completes the transaction. It’s not the most elegant or quickest way to do business, but it’s another option when you’re in a pinch.

Now all Google needs to do is get more people using Google Checkout.


"

Magento webshop on android


Magento is an eCommerce platform, and they are working on releasing their mCommerce platform for Android/iPhone/iPad this august.

Check Internet Connection Android

private boolean CheckInternet() {
ConnectivityManager connec = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
return true;
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity ! ").setCancelable(
false).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return false;
}
}

Wednesday, June 30, 2010

Delete Specific File From Sdcard in Android

//======== Delete Specific File From SDCARD ======================


private void deleteFile() {
File list = new File(Environment.getExternalStorageDirectory() + "/Directory Name/");
File[] vidlist = list.listFiles(new FilenameFilter() {

public boolean accept(File dir, String filename) {
return ((filename.endsWith(".temp")));
}
});


for (int i = 0; i < vidlist.length; i++) {
vidlist[i].delete();
}
}

Get Device ID in Android

//======== Get Device ID ======================
public void getDeviceID() {
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
DEVICE_ID = TelephonyMgr.getDeviceId();
}