Know Android Phone rooted through programme

 

To know weather the android phone is rooted or not through program, call the below method:

 

    public boolean isRooted() {
        
        boolean rooted = false;
        try {
            File su = new File(“/system/bin/su”);
            if (su.exists() == true) {
                su = new File(“/system/xbin/su”);
                if (su.exists() == true) {
                    rooted = true;
                }
            }
        } catch (Exception e) {
            Log.d(“My Activity”, “Exception is: “+e.getMessage());
            rooted = false;
        }
        return rooted;
    }

 

If the Phone is rooted it returns “true” and if not then “false”.

Leave a comment

Filed under Uncategorized

Android Fragments Support for 2.x

To Use Android Fragements in Android 2.3 and lesser version, please follow the below steps:

Import android-support-v4.jar in to your project  (change android-support-v4.jar .png to android-support-v4.jar ).

Create FragmentLayoutSupport.java which extends FragmentActivity.

*************************************************

package com.frag.testone;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

/**
* Demonstration of using fragments to implement different activity layouts.
* This sample provides a different layout (and activity flow) when run in
* landscape.
*/
public class FragmentLayoutSupport extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.fragment_layout_support);
}

/**
* This is a secondary activity, to show what the user has selected
* when the screen is not large enough to show it all in one activity.
*/

public static class DetailsActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don’t need this activity.
finish();
return;
}

if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}

/**
* This is the “top-level” fragment, showing a list of items that the
* user can pick.  Upon picking an item, it takes care of displaying the
* data to the user as appropriate based on the currrent UI layout.
*/

public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;

public TitlesFragment() {

}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.simple_list_item_checkable_1,
android.R.id.text1, Shakespeare.TITLES));

// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt(“curChoice”, 0);
}

if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(“curChoice”, mCurCheckPosition);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}

/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;

if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);

// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);

// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}

} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra(“index”, index);
startActivity(intent);
}
}
}

/**
* This is the secondary fragment, displaying the details of a particular
* item.
*/

public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at ‘index’.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();

// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt(“index”, index);
f.setArguments(args);

return f;
}

public int getShownIndex() {
return getArguments().getInt(“index”, 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment’s containing frame doesn’t exist.  The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won’t be displayed.  Note this is not needed — we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}

ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}

}
******************************************************************

fragment_layout_support.xml is set the View.

<FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent” android:layout_height=”match_parent”>
<fragment         class=”com.frag.testone.FragmentLayoutSupport$TitlesFragment”
android:id=”@+id/titles”
android:layout_width=”match_parent” android:layout_height=”match_parent” />
</FrameLayout>

TitlesFragment extends ListFragment.

****************************************************************

simple_list_item_checkable_1.xml is used to select the title (which is in left side of screen)

<com.frag.testone.CheckableFrameLayout
xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<TextView
android:id=”@android:id/text1″
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:textAppearance=”?android:attr/textAppearanceLarge”
android:minHeight=”?android:attr/listPreferredItemHeight”
android:gravity=”center_vertical”
/>
</com.frag.testone.CheckableFrameLayout>

*****************************************************************

package com.frag.testone;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.FrameLayout;

public class CheckableFrameLayout extends FrameLayout implements Checkable {
private boolean mChecked;

public CheckableFrameLayout(Context context) {
super(context);
}

public CheckableFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}

public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? new ColorDrawable(0xff0000a0) : null);
}

public boolean isChecked() {
return mChecked;
}

public void toggle() {
setChecked(!mChecked);
}

}

***************************************************************

Shakespeare class contains the data we populate in UI.

package com.frag.testone;

public final class Shakespeare {
/**
* Our data, part 1.
*/
public static final String[] TITLES =
{
“Henry IV (1)”,
“Henry V”,
“Henry VIII”,
“Richard II”,
“Richard III”,
“Merchant of Venice”,
“Othello”,
“King Lear”
};

/**
* Our data, part 2.
*/
public static final String[] DIALOGUE =
{
“So shaken as we are, so wan with care,” +
“Find we a time for frighted peace to pant,” +
“And breathe short-winded accents of new broils” +
“To be commenced in strands afar remote.” +
“No more the thirsty entrance of this soil” +
“Shall daub her lips with her own children’s blood;” +
“Nor more shall trenching war channel her fields,” +
“Nor bruise her flowerets with the armed hoofs” +
“Of hostile paces: those opposed eyes,” +
“Which, like the meteors of a troubled heaven,” +
“All of one nature, of one substance bred,” +
“Did lately meet in the intestine shock” +
“And furious close of civil butchery” +
“Shall now, in mutual well-beseeming ranks,” +
“March all one way and be no more opposed” +
“Against acquaintance, kindred and allies:” +
“The edge of war, like an ill-sheathed knife,” +
“No more shall cut his master. Therefore, friends,” +
“As far as to the sepulchre of Christ,” +
“Whose soldier now, under whose blessed cross” +
“We are impressed and engaged to fight,” +
“Forthwith a power of English shall we levy;” +
“Whose arms were moulded in their mothers’ womb” +
“To chase these pagans in those holy fields” +
“Over whose acres walk’d those blessed feet” +
“Which fourteen hundred years ago were nail’d” +
“For our advantage on the bitter cross.” +
“But this our purpose now is twelve month old,” +
“And bootless ’tis to tell you we will go:” +
“Therefore we meet not now. Then let me hear” +
“Of you, my gentle cousin Westmoreland,” +
“What yesternight our council did decree” +
“In forwarding this dear expedience.”,

“Hear him but reason in divinity,” +
“And all-admiring with an inward wish” +
“You would desire the king were made a prelate:” +
“Hear him debate of commonwealth affairs,” +
“You would say it hath been all in all his study:” +
“List his discourse of war, and you shall hear” +
“A fearful battle render’d you in music:” +
“Turn him to any cause of policy,” +
“The Gordian knot of it he will unloose,” +
“Familiar as his garter: that, when he speaks,” +
“The air, a charter’d libertine, is still,” +
“And the mute wonder lurketh in men’s ears,” +
“To steal his sweet and honey’d sentences;” +
“So that the art and practic part of life” +
“Must be the mistress to this theoric:” +
“Which is a wonder how his grace should glean it,” +
“Since his addiction was to courses vain,” +
“His companies unletter’d, rude and shallow,” +
“His hours fill’d up with riots, banquets, sports,” +
“And never noted in him any study,” +
“Any retirement, any sequestration” +
“From open haunts and popularity.”,

“I come no more to make you laugh: things now,” +
“That bear a weighty and a serious brow,” +
“Sad, high, and working, full of state and woe,” +
“Such noble scenes as draw the eye to flow,” +
“We now present. Those that can pity, here” +
“May, if they think it well, let fall a tear;” +
“The subject will deserve it. Such as give” +
“Their money out of hope they may believe,” +
“May here find truth too. Those that come to see” +
“Only a show or two, and so agree” +
“The play may pass, if they be still and willing,” +
“I’ll undertake may see away their shilling” +
“Richly in two short hours. Only they” +
“That come to hear a merry bawdy play,” +
“A noise of targets, or to see a fellow” +
“In a long motley coat guarded with yellow,” +
“Will be deceived; for, gentle hearers, know,” +
“To rank our chosen truth with such a show” +
“As fool and fight is, beside forfeiting” +
“Our own brains, and the opinion that we bring,” +
“To make that only true we now intend,” +
“Will leave us never an understanding friend.” +
“Therefore, for goodness’ sake, and as you are known” +
“The first and happiest hearers of the town,” +
“Be sad, as we would make ye: think ye see” +
“The very persons of our noble story” +
“As they were living; think you see them great,” +
“And follow’d with the general throng and sweat” +
“Of thousand friends; then in a moment, see” +
“How soon this mightiness meets misery:” +
“And, if you can be merry then, I’ll say” +
“A man may weep upon his wedding-day.”,

“First, heaven be the record to my speech!” +
“In the devotion of a subject’s love,” +
“Tendering the precious safety of my prince,” +
“And free from other misbegotten hate,” +
“Come I appellant to this princely presence.” +
“Now, Thomas Mowbray, do I turn to thee,” +
“And mark my greeting well; for what I speak” +
“My body shall make good upon this earth,” +
“Or my divine soul answer it in heaven.” +
“Thou art a traitor and a miscreant,” +
“Too good to be so and too bad to live,” +
“Since the more fair and crystal is the sky,” +
“The uglier seem the clouds that in it fly.” +
“Once more, the more to aggravate the note,” +
“With a foul traitor’s name stuff I thy throat;” +
“And wish, so please my sovereign, ere I move,” +
“What my tongue speaks my right drawn sword may prove.”,

“Now is the winter of our discontent” +
“Made glorious summer by this sun of York;” +
“And all the clouds that lour’d upon our house” +
“In the deep bosom of the ocean buried.” +
“Now are our brows bound with victorious wreaths;” +
“Our bruised arms hung up for monuments;” +
“Our stern alarums changed to merry meetings,” +
“Our dreadful marches to delightful measures.” +
“Grim-visaged war hath smooth’d his wrinkled front;” +
“And now, instead of mounting barded steeds” +
“To fright the souls of fearful adversaries,” +
“He capers nimbly in a lady’s chamber” +
“To the lascivious pleasing of a lute.” +
“But I, that am not shaped for sportive tricks,” +
“Nor made to court an amorous looking-glass;” +
“I, that am rudely stamp’d, and want love’s majesty” +
“To strut before a wanton ambling nymph;” +
“I, that am curtail’d of this fair proportion,” +
“Cheated of feature by dissembling nature,” +
“Deformed, unfinish’d, sent before my time” +
“Into this breathing world, scarce half made up,” +
“And that so lamely and unfashionable” +
“That dogs bark at me as I halt by them;” +
“Why, I, in this weak piping time of peace,” +
“Have no delight to pass away the time,” +
“Unless to spy my shadow in the sun” +
“And descant on mine own deformity:” +
“And therefore, since I cannot prove a lover,” +
“To entertain these fair well-spoken days,” +
“I am determined to prove a villain” +
“And hate the idle pleasures of these days.” +
“Plots have I laid, inductions dangerous,” +
“By drunken prophecies, libels and dreams,” +
“To set my brother Clarence and the king” +
“In deadly hate the one against the other:” +
“And if King Edward be as true and just” +
“As I am subtle, false and treacherous,” +
“This day should Clarence closely be mew’d up,” +
“About a prophecy, which says that ‘G'” +
“Of Edward’s heirs the murderer shall be.” +
“Dive, thoughts, down to my soul: here” +
“Clarence comes.”,

“To bait fish withal: if it will feed nothing else,” +
“it will feed my revenge. He hath disgraced me, and” +
“hindered me half a million; laughed at my losses,” +
“mocked at my gains, scorned my nation, thwarted my” +
“bargains, cooled my friends, heated mine” +
“enemies; and what’s his reason? I am a Jew. Hath” +
“not a Jew eyes? hath not a Jew hands, organs,” +
“dimensions, senses, affections, passions? fed with” +
“the same food, hurt with the same weapons, subject” +
“to the same diseases, healed by the same means,” +
“warmed and cooled by the same winter and summer, as” +
“a Christian is? If you prick us, do we not bleed?” +
“if you tickle us, do we not laugh? if you poison” +
“us, do we not die? and if you wrong us, shall we not” +
“revenge? If we are like you in the rest, we will” +
“resemble you in that. If a Jew wrong a Christian,” +
“what is his humility? Revenge. If a Christian” +
“wrong a Jew, what should his sufferance be by” +
“Christian example? Why, revenge. The villany you” +
“teach me, I will execute, and it shall go hard but I” +
“will better the instruction.”,

“Virtue! a fig! ’tis in ourselves that we are thus” +
“or thus. Our bodies are our gardens, to the which” +
“our wills are gardeners: so that if we will plant” +
“nettles, or sow lettuce, set hyssop and weed up” +
“thyme, supply it with one gender of herbs, or” +
“distract it with many, either to have it sterile” +
“with idleness, or manured with industry, why, the” +
“power and corrigible authority of this lies in our” +
“wills. If the balance of our lives had not one” +
“scale of reason to poise another of sensuality, the” +
“blood and baseness of our natures would conduct us” +
“to most preposterous conclusions: but we have” +
“reason to cool our raging motions, our carnal” +
“stings, our unbitted lusts, whereof I take this that” +
“you call love to be a sect or scion.”,

“Blow, winds, and crack your cheeks! rage! blow!” +
“You cataracts and hurricanoes, spout” +
“Till you have drench’d our steeples, drown’d the cocks!” +
“You sulphurous and thought-executing fires,” +
“Vaunt-couriers to oak-cleaving thunderbolts,” +
“Singe my white head! And thou, all-shaking thunder,” +
“Smite flat the thick rotundity o’ the world!” +
“Crack nature’s moulds, an germens spill at once,” +
“That make ingrateful man!”
};
}

**************************************************************

Leave a comment

Filed under Uncategorized

My Apps in Stores

Google Play:

Backup Contacts 2 SpreadSheet:

https://market.android.com/details?id=com.pr.backupcontacts.ui&feature=search_result

Do not Touch Me:

https://market.android.com/details?id=com.pr.touchmenot.ui&feature=search_result

Notifier:

https://market.android.com/details?id=com.pr.notifier.ui&feature=search_result

Optimizer:

https://market.android.com/details?id=com.pr.backgroundappkillerbyservice.ui&feature=search_result

VirtalFan:

https://play.google.com/store/apps/details?id=com.pr.virtualfan.ui&feature=search_result

Make Ur Kolaveri Di:

https://play.google.com/store/apps/details?id=com.pr.urkolaveridi.ui&feature=search_result

SnoozeThenStopAlarm:

https://play.google.com/store/apps/details?id=com.pr.snoozethenstopalarm&hl=en

Windows Phone Market:

Virtual Fan

http://www.windowsphone.com/en-us/store/app/virtualfan/43bc3715-93cb-4714-a539-7e0023e052f2

BlackBerry App World:

VirtauFan:

http://appworld.blackberry.com/webstore/content/117133/?lang=en

Leave a comment

Filed under Uncategorized

Android dialog listview for multi selection

 

We are not going to use any thing from xml file.

package com.pr.testtwo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class TestTwoActivity extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final CharSequence[] digitList= { “One”, “Two”, “Three” };
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setIcon(R.drawable.icon);
alt_bld.setTitle(“Select one Digit”);

alt_bld.setMultiChoiceItems(digitList, new boolean[] { false, true,
false },
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {

}
});
alt_bld.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

ListView list = ((AlertDialog)dialog).getListView();

StringBuilder sb = new StringBuilder();
for (int i=0; i<list.getCount(); i++) {
boolean checked = list.isItemChecked(i);

if (checked) {
if (sb.length()>0) sb.append(“, “);
sb.append(list.getItemAtPosition(i));
}
}

Toast.makeText(getApplicationContext(),
“Selected digit: ” + sb.toString(),
Toast.LENGTH_SHORT).show();

}
});
alt_bld.setNegativeButton(“Cancel”,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});

AlertDialog alert = alt_bld.create();
alert.show();

}

}

Leave a comment

Filed under Uncategorized

Android dialog listview for single selection

 

We are not going to use any thing from xml file,

Please copy and paste below code:

package com.pr.testtwo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TestTwoActivity extends Activity {
/** Called when the activity is first created. */
private Gallery gallery;
private int selectedItem;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final CharSequence[] digitList = { “One”, “Two”, “Three” };
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setIcon(R.drawable.icon);
alt_bld.setTitle(“Select one Digit”);
selectedItem = -1;
alt_bld.setSingleChoiceItems(digitList , -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
selectedItem = item;
}
});
alt_bld.setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
“Selected digit: ” + digitList [selectedItem],
Toast.LENGTH_SHORT).show();

}
});
alt_bld.setNegativeButton(“Cancel”,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});

AlertDialog alert = alt_bld.create();
alert.show();
}
}

Leave a comment

Filed under Uncategorized

Android Date Time example

Please follow the 2 steps to implement Date and Time picker in application.

1. create xm like  “main.xml”

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:orientation=”vertical” android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView android:layout_width=”fill_parent”
android:layout_height=”wrap_content” android:text=”@string/hello” />
<RelativeLayout android:orientation=”vertical”
android:layout_width=”fill_parent” android:layout_height=”fill_parent”>
<Button android:id=”@+id/timepicker” android:layout_width=”121px”
android:layout_height=”wrap_content” android:text=”Time Picker”
android:layout_alignParentTop=”true” android:layout_alignParentRight=”true”>
</Button>
<Button android:id=”@+id/datepicker” android:layout_width=”122px”
android:layout_height=”wrap_content” android:text=”Date Picker”
android:layout_alignParentTop=”true” android:layout_alignParentLeft=”true”>
</Button>
</RelativeLayout>
</LinearLayout>

2. Append an event listner in Activity like below:

package com.pr.testone;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class TestOneActivity extends Activity implements Button.OnClickListener{
private Button b1, b2;
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Adding button to the layout
b1 = (Button) findViewById(R.id.datepicker);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.timepicker);
b2.setOnClickListener(this);

}

// Creating dialog
@Override
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth,
cday);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, 0, 0,false);
}
return null;
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
// onDateSet method
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
String date_selected = String.valueOf(monthOfYear + 1) + ” /”
+ String.valueOf(dayOfMonth) + ” /” + String.valueOf(year);
Toast.makeText(TestOneActivity.this,
“Selected Date is =” + date_selected, Toast.LENGTH_SHORT)
.show();
}
};

private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(TestOneActivity.this, “Time is=”+hourOfDay+”:”+minute, Toast.LENGTH_SHORT).show();
}
};

@Override
public void onClick(View v) {
if (v == b1){
showDialog(DATE_DIALOG_ID);
}else if (v == b2) {
showDialog(TIME_DIALOG_ID);
}
}
}

The result will be as shown in screen captures.

Leave a comment

Filed under Uncategorized

Android AIDL Example

Steps for aidl implemenation:
1.
Create aidl file in src folder as below.
SaInterface.aidl
**********************************
package com.sample.aidl.ui;

interface SAInterface {
String getDownloadFilename (in String name);
}
**********************************
2.
Implement getDownloadFilename(String) method in Service extended class as below.

**********************************
package com.sample.aidl.ui;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class AidlService extends Service {

@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}

private final SAInterface.Stub mBinder = new SAInterface.Stub() {
public String getDownloadFilename(String name) throws RemoteException {
return “You are downloading” + name + “file.”;
}
};
}
*********************************
3.
Make a service call in AidlActivity.

*********************************
package com.sample.aidl.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class AidlActivity extends Activity {

private SAInterface saInterface;
private Context mContext = this;

private String TAG = AidlActivity.class.getSimpleName();
private static final int PROGRESS = 0xDEADBEEF;

private Handler mHandler = new Handler(){

public void handleMessage(android.os.Message msg) {
if (msg.what == PROGRESS) {
try {
String DownloadfileName = saInterface.getDownloadFilename(“AIDL Checking!”);
Log.d(TAG, “DownloadfileName: “+DownloadfileName);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
};

private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
saInterface = SAInterface.Stub.asInterface(service);
}

public void onServiceDisconnected(ComponentName className) {
saInterface = null;
}
};

/** Called with the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
//bind the ServiceConnection object to activity.
mContext.bindService(new Intent(AidlActivity .this,
AidlService.class), mConnection, Context.BIND_AUTO_CREATE);
mHandler.sendMessageDelayed(mHandler.obtainMessage(PROGRESS), 500);
}

@Override
protected void onDestroy() {
// unbind the ServiceConnection object from activity to avoid ServiceConnectionLeaked error.
mContext.unbindService(mConnection);
super.onDestroy();
}
}
*******************************

now check the logcat.

Leave a comment

Filed under Uncategorized