Search...

Tuesday, April 24, 2012

How to use TimerTask in Android?



public class Test extends Activity {
    /** Called when the activity is first created. */
Timer myTimer=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        MyTimerTask myTask = new MyTimerTask();
        myTimer = new Timer();
        myTimer.schedule(myTask, 3000, 1500);
       
        Button b=(Button)findViewById(R.id.button1);
     
        b.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

myTimer.cancel();
System.out.println("Cancel the timer...");

}
});
       
     
       
    }
   
   
    class MyTimerTask extends TimerTask {
   public void run() {
   // ERROR
     System.out.println("TimerTask is running......");
   }
  }
}

Friday, April 20, 2012

How to open URL in browser in Android?


        Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url.toString().trim()));
startActivity(i);

How to send email in Android?


    Intent sendIntent = new Intent(Intent.ACTION_SEND);
// Set Address for Email
sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
// Set Subject for Email
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Test");

sendIntent.putExtra(Intent.EXTRA_TEXT, "Expense Category:");

// Attach picture to email
Uri imageFile = Uri.parse("file://" + imagePath);
sendIntent.putExtra(Intent.EXTRA_STREAM, imageFile);

startActivity(Intent.createChooser(sendIntent, "Choose your e-mail"));

Monday, April 2, 2012

How to find the Version of the app in Android?


PackageManager pm = getPackageManager();
 PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);
     
 System.out.println("Version Name :"+packageInfo.versionName);
 System.out.println("Version Code :"+packageInfo.versionCode);

Saturday, March 24, 2012

How to know when TTS is finished in Android?


public class TTSActivity extends Activity implements OnInitListener, OnUtteranceCompletedListener, ... {
private TextToSpeech mTts;
...........
private void speak(String text) {
   if(text != null) {
      HashMap<String, String> myHashAlarm = new HashMap<String, String>();
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
      myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
      mTts.speak(text, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
   }
}
// Fired after TTS initialization
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS) {
        mTts.setOnUtteranceCompletedListener(this);
    }
}
// It's callback
public void onUtteranceCompleted(String utteranceId) {
   Log.i(TAG, utteranceId); //utteranceId == "SOME MESSAGE"
   }
...........
}

Tuesday, March 20, 2012

How to read contacts on Android ?


First, ensure that you have added android.permission.READ_CONTACTS to your AndroidManifest.xml file, then you can loop through your phone contacts like this:


Code:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
   String contactId = cursor.getString(cursor.getColumnIndex(
   ContactsContract.Contacts._ID));
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
   if (Boolean.parseBoolean(hasPhone)) {
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
      while (phones.moveToNext()) {
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));                
      }
   phones.close();
}

Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
   // This would allow you get several email addresses
   String emailAddress = emails.getString(
   emails.getColumnIndex(ContactsContract.CommonDataKinds.CommonDataColumns.DATA));
}
emails.close();
cursor.close();

How to Listen For Incoming SMS Messages in Android?

Step1



<uses-permission id="android.permission.RECEIVE_SMS" />

    <application>

        <receiver class=".TestSMSApp">
            <intent-filter>

                <action android:value="android.provider.Telephony.SMS_RECEIVED" />

            </intent-filter>
        </receiver>

    </application>

Step2:



package org.apache.sms;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Log;
import android.telephony.gsm.SmsMessage;

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

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

    public void onReceiveIntent(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION)) {

           Bundle bundle = intent.getExtras();      
        SmsMessage[] msgs = null;
        String str = "";          
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];          
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);              
                str += "SMS from " + msgs[i].getOriginatingAddress();                    
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";      
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
         
            }
         
          }
        }
   }

   




How to Retrieve incoming call’s phone number in Android?

Step1: Add Below code in your manifest file


 <receiver android:name=".CallBroadcastReceiver">
        <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />    
        </intent-filter>
</receiver>

</application>
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />


Step2: Create class to receive Broadcast message




public class CallBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
   
 String action = intent.getAction();

           if(action.equalsIgnoreCase("android.intent.action.PHONE_STATE")){
              if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                                  TelephonyManager.EXTRA_STATE_RINGING)) {
                  //Incoming call
               doSomething(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
              }
}



Thursday, March 15, 2012

How to changing the ringer volume in Android?


Step1:

Create one layout with seekbar view(main.xml)

Step2:



import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class VolumeActivity extends Activity
{

//a variable to store the seek bar from the XML file
private SeekBar volumeBar;

//an AudioManager object, to change the volume settings
private AudioManager amanager;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //get the seek bar from main.xml file
        volumeBar = (SeekBar) findViewById(R.id.sb_volumebar);

        //get the audio manager
        amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

        //seek bar settings//
        //sets the range between 0 and the max volume
        volumeBar.setMax(amanager.getStreamMaxVolume(AudioManager.STREAM_RING));
        //set the seek bar progress to 1
        volumeBar.setKeyProgressIncrement(1);

        //sets the progress of the seek bar based on the system's volume
        volumeBar.setProgress(amanager.getStreamVolume(AudioManager.STREAM_RING));

        //register OnSeekBarChangeListener, so that the seek bar can change the volume
volumeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}

@Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//change the volume, displaying a toast message containing the current volume and playing a feedback sound
amanager.setStreamVolume(AudioManager.STREAM_RING, progress, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
}
});
    }

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//if one of the volume keys were pressed
if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
//change the seek bar progress indicator position
volumeBar.setProgress(amanager.getStreamVolume(AudioManager.STREAM_RING));
}
//propagate the key event
return super.onKeyDown(keyCode, event);
}
}

How to close/hide the Android Soft Keyboard?



You can force Android to hide the virtual keyboard using the InputMethodManager, callinghideSoftInputFromWindow, passing in the token of the window containing your edit field.

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Monday, March 12, 2012

How to use AlarmManager to update widget(remoteview) in Android?

How to make widget(remoteview) in Android?

How to find out that service is running or not in Android?


private boolean isMyServiceRunning() {
   ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
   for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
       if ("com.test.DataService".equals(service.service.getClassName())) {
           return true;
       }
   }
   return false;
}

Saturday, March 10, 2012

How to shadow on text in android?


Step1


You should be able to add the style, like this (taken from source code for Ringdroid):

  <style name="AudioFileInfoOverlayText">
    <item name="android:paddingLeft">4px</item>
    <item name="android:paddingBottom">4px</item>
    <item name="android:textColor">#ffffffff</item>
    <item name="android:textSize">12sp</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
  </style>

Step2


And in your layout, use the style like this:

 <TextView android:id="@+id/info"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       style="@style/AudioFileInfoOverlayText"
       android:gravity="center" />

Thursday, March 8, 2012

How to integrate AdMob in android app?



-Register or login at admob.com, and click 'Sites & Apps".
-Click "Add Site/App", and provide the info for your Android App. (Feel free to enter placeholder information if you just want to download the SDK without registering a real app.)
-Once you've added your site, you will be prompted to download the Android SDK and the integration PDF.
-The download includes the binaries, documentation, and a sample.
-Review the integration PDF at http://www.admob.com/docs/AdMob_Android_SDK_Instructions.pdf
-Read index.html for information on the AdMob SDK's classes and methods
-Look at the Lunar Lander sample project to see a working example
-For more info you should check http://developer.admob.com/wiki/Android

Note: Description for you app/site on admob is very important, they use all info that appear there to provide your advertisement.

Wednesday, March 7, 2012

How to create Transparent Activity in Android?


Step1

Add the following style In your res/values/styles.xml file (if you don’t have one, create it.) Here’s a complete file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>
</resources>
(the value @color/transparent is the color value #00000000 which I put in res/values/color.xml file. You can also use @android:color/transparent in later Android versions)

Step2

Then apply the style to your activity, for example:

<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...
</activity>

Tuesday, March 6, 2012

how to set the type of application in twitter?


They not using the concept of "application type" (browser / client)
anymore. For an Android application, you probably want to do the full
(callback-based) OAuth flow, so you should specify a callback URL in your
Application Settings (and declare your oauth_callback for each request
token step you make). Now if you wanted to use the PIN/out-of-band flow,
simply enter "oob" as your Callback URL.

Monday, March 5, 2012

How to change TextView Color when user pressed or Clicked TextView in android?


Step 1: Create an XML under
res/color/text_color.xml
as shown below

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#ffff0000"/> <!-- pressed -->
    <item android:state_focused="true"
          android:color="#ff0000ff"/> <!-- focused -->
    <item android:color="#ff000000"/> <!-- default -->
</selector>

Step2:  Apply it to TextView as i shown below

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:textColor="@color/
text_color
" />

Monday, February 27, 2012

How to change colour of activated list item background on Honeycomb android?


(1) background_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
        >
 
 
    <item android:state_activated="true" android:drawable="@drawable/hilight_blu" />

    <item android:state_activated="true"  android:drawable="@drawable/hilight_blu"/>

    <item android:state_focused="true" android:state_enabled="false"
        android:state_pressed="true"
        android:drawable="@drawable/hilight_blu" />
     
     <item android:state_focused="true" android:state_selected="true" android:state_pressed="false"      android:drawable="@drawable/hilight_blu"/>
    <item android:state_focused="true" android:state_enabled="false"
        android:drawable="@drawable/hilight_blu" />

    <item android:state_focused="true" android:state_pressed="true"
        android:drawable="@drawable/hilight_blu" />
     
    <item android:state_focused="false" android:state_pressed="true"
        android:drawable="@drawable/hilight_blu" />
     
         <item android:state_focused="false" android:state_selected="true"
        android:drawable="@drawable/hilight_blu" />

    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false"     android:drawable="@drawable/hilight_blu"/>
 
     <item android:drawable="@color/transparent" />
 </selector>

(2) list_item.xml




  <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="11dp" android:background="@drawable/background_selector"
    android:paddingBottom="11dp"
    android:paddingLeft="23dp" android:textAppearance="@style/sans17white">
</TextView>


(3)Setting the adapter values.

ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
getActivity(), R.layout.list_item,getCustomCategory());
categoryList.setAdapter(adapter);
categoryList.setOnItemClickListener(categoryListener);

(4)Selecting item



AdapterView.OnItemClickListener categoryListener = new AdapterView.OnItemClickListener() {

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {


selectListItem(arg2);


}

};









How to set Bitmap images from a file stored inside a SD-Card in Android?


File imgFile = new  File(“/sdcard/Images/test_image.jpg”);

if(imgFile.exists()){


    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());


    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

    myImage.setImageBitmap(myBitmap);


}

How to show Top-most and Bottom-most Horizonal Divider in ListView in android??


Sample example:

 You have to give some bottom and top padding in list view
<ListView android:id="@+id/test"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:divider="@drawable/line_horiz"
android:dividerHeight="2dp" android:footerDividersEnabled="true"                         android:headerDividersEnabled="true" android:paddingTop="10dp"
       android:paddingBottom="10dp"/>

How to go to home activity by removing the in between activities on the stack in android??


Suppose you user went to A->B->C->D activities and now user wanted to again come to activity A(HomeActivity)from D activity. Use the following code.

            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

How to clear task stack to finish all activity in android?


Intent i = new Intent(this MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


startActivity(i);

       finish();


This code will close all the opened activities and start new activity as root one.

How to use Special Chracter’s in Android Layout XML?


Backslashing double quotes will not work in a XML layout. You should use the HTML-code (quot), like this:
<TextView android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:text="Here goes my &quot;escaped&quot; text!" />

The above code will display a TextView containing:
Here goes my "escaped" text!
XML has 5 of these predifined entities:
&quot;   "
&amp;    &
&apos;   '
&lt;     <
&gt;     >