public class MaxLengthWatcher implements TextWatcher {
private int maxLen = 0;
private EditText editText = null;
public MaxLengthWatcher(int maxLen, EditText editText) {
this.maxLen = maxLen;
this.editText = editText;
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Editable editable = editText.getText();
int len = editable.length();
if(len > maxLen)
{
int selEndIndex = Selection.getSelectionEnd(editable);
String str = editable.toString();
//Interception of a new string
String newStr = str.substring(0,maxLen);
editText.setText(newStr);
editable = editText.getText();
int newLen = editable.length();
if(selEndIndex > newLen)
{
selEndIndex = editable.length();
}
//Set the new cursor position
Selection.setSelection(editable, selEndIndex);
}
}
}
TextWatcherActivity.java :
public class TextWatcherActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText editText = (EditText) findViewById(R.id.entry);
editText.addTextChangedListener(new MaxLengthWatcher(10, editText));
}
}
In Android,Toast is a notification message that usees to displays a message to the user and message will disappear automatically after a certain period of time.
Information can be simple text, it can be complex pictures and other content (shows a view) .
Spinner is a widget similar to a drop-down list for selecting items.
In this post, you'll create a simple spinner widget that displays a list of countries and implements OnItemSelectedListener When item is selected,
a toast message will display the selected item.
STEP 1: Start a new project named AndroidSpinnerExample.
STEP 2: Open the res\layout\main.xml file and insert the following code:
SlidingDrawer hides content out of the screen and allows the user to drag a handle to bring the content on screen. SlidingDrawer can be used vertically or horizontally. A special widget composed of two children views: the handle, that the users drags, and the content, attached to the handle and dragged with it. SlidingDrawer should be used as an overlay inside layouts. This means SlidingDrawer should only be used inside of a FrameLayout or a RelativeLayout for instance. The size of the SlidingDrawer defines how much space the content will occupy once slid out so SlidingDrawer should usually use match_parent for both its dimensions. Inside an XML layout, SlidingDrawer must define the id of the handle and of the content.
Two important methods of SlidingDrawer :
Gallery is an internal element which can scroll horizontally and layout component of the currently selected child elements are positioned in the center of it.
STEP 1: Creating a new project from File->New->Android Project with Gallerydemo Activity Name
STEP 2: Copy Image files to res/drawable Folder
STEP 3: In res/layout/main.xm layout add ImageView and Gallery View as:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- ImageView for display image in background -->
<ImageView
android:id="@+id/imgview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/a01"
/>
<!-- Gallery To show images Gallery -->
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/galleryview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spacing="5dp"
/>
</FrameLayout >
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.
Clients send requests through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread.
The IntentService class exists to simplify this pattern and take care of the mechanics.
To use it, extend IntentService and implement onHandleIntent(Intent).
IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread - they may take as long as necessary (and will not block the application's main loop),
but only one request will be processed at a time.
IntentService is a subclass of Service, and can handle asynchronous requests (with Intent).
Service can be started when needed, and a separate thread to handle each Intent to, but after processing will be canceled.
The work queue processor is generally used for the task from the application's main thread.
All requests will be handled in a separate thread, but not blocking the main thread of the application. And time to process a request.
Service vs IntentService:
Service class uses the application’s main thread, while IntentService creates a worker thread and uses that thread to run the service.
IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly.
Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when there is no intent in queue.
IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().
Service vs Thread vs AsyncTask:
Threads or Async task perform their tasks in a background thread thus they do not block the main thread, while a service performs it’s work in the main thread. so if a service is performing an intensive task such as calling a web service, it may block the main thread until it finishes. So for intensive tasks a service should run it’s work in a background thread.
A service runs in the same process of the application and keeps running until stopped by itself, stopped by the user or killed by the system if it needs memory.
IntentService of example:
In IntentServiceActivity.java: :
package com.imrankhanandroid.Intentserviceexp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class IntentServiceActivity extends Activity {
private TextView text;
private Button btnStart;
private Button btnSendOther;
private MessageReceiver receiver ;
// Action
private static final String ACTION_RECV_MSG =
"com.imrankhanandroid.intent.action.RECEIVE_MESSAGE";
private static final String ACTION_OTHER_MSG =
"com.imrankhanandroid.intent.action.OTHER_MESSAGE";
// Message
private static final String MESSAGE_IN="message_input";
private static final String MESSAGE_OUT="message_output";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.text);
text.setText("Preparation");
btnStart=(Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent msgIntent = new Intent(IntentServiceActivity.this,
IntentServicetest.class);
text.setText("");
msgIntent.putExtra(MESSAGE_IN, text.getText().toString());
startService(msgIntent);
}
});
btnSendOther=(Button)findViewById(R.id.btnSendOther);
btnSendOther.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
//Dynamic registration Receiver
IntentFilter filter = new IntentFilter(ACTION_RECV_MSG);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MessageReceiver();
registerReceiver(receiver, filter);
IntentFilter filter2 = new IntentFilter(ACTION_OTHER_MSG);
filter2.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MessageReceiver();
registerReceiver(receiver, filter2);
}
//Broadcast to receive
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra(MESSAGE_OUT);
text.setText(message);
Toast.makeText(context, "message",Toast.LENGTH_SHORT).show();
}
}
}
In IntentServicetest.java: :
package com.imrankhanandroid.Intentserviceexp;
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;
// IntentService
public class IntentServicetest extends IntentService {
// Action
private static final String ACTION_RECV_MSG =
"com.imrankhanandroid.intent.action.RECEIVE_MESSAGE";
// Message
private static final String MESSAGE_IN="message_input";
private static final String MESSAGE_OUT="message_output";
private final static String Tag="---IntentServicetest";
public IntentServicetest() {
// TODO Auto-generated constructor stub
super("IntentServicetest");
Log.d(Tag, "Constructor");
}
@Override
public void onDestroy() {
Log.d(Tag, "onDestroy()");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(Tag, "onStart()");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Tag, "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void setIntentRedelivery(boolean enabled) {
Log.d(Tag, "setIntentRedelivery()");
super.setIntentRedelivery(enabled);
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.d(Tag, "IntentServicetest is onHandleIntent!");
String msgRecv = intent.getStringExtra(MESSAGE_IN);
Log.d(Tag, msgRecv);
for (int i = 0; i < 5; i++) {
String resultTxt = msgRecv + " "
+ DateFormat.format("MM/dd/yy hh:mm:ss",
System.currentTimeMillis());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_RECV_MSG);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(MESSAGE_OUT, resultTxt);
sendBroadcast(broadcastIntent);
SystemClock.sleep(1000);
}
}
}