Technical Knowledge

technical knowledge is that type of blogger in which you can find all the soluctions of your problems which you cannot solve you can see the video given on this blog and solve your problem by yourself.

Like us on Facebook

Technical Knowledge
Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Sunday, March 29, 2015

options menu, context menu, and sub menu: android tutorial

Program description:

This program will show how to design, create, and handle menus in android.

There are 3 types menus:

1. Options menu - displayed when user clicks hard menu key on the keyboard
2. Sub menu - menu with in a menu
3. Context menu - press and hold on a view, to show context menu.
                                just like when you right click on some item in your desktop.

This will show how to create options menu, how to handle option menu items &

How to register context menu for a button, and how to handle context menu items.

Note: From android version 3.0 on wards there is no support for hard key menu, so using options menu is discouraged. In place of options menu we will be using action bars.


First Activity
package com.techpalle.b15_menus;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
registerForContextMenu(b1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if(v.getId() == R.id.button1){

}
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.contextmenu, menu);
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("Contact Us!");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),
"Contact by SMS", 0).show();
break;
case R.id.item2:
Toast.makeText(getApplicationContext(),
"Contact by Call", 0).show();
break;
case R.id.item3:
Toast.makeText(getApplicationContext(),
"Contact by Map location", 0).show();
break;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.optionsmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setTitle("My home");
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(), "Home", 0).show();
break;
case R.id.item2:
Toast.makeText(getApplicationContext(), "AboutUs", 0).show();
break;
case R.id.item3:
item.getSubMenu().setHeaderIcon(R.drawable.ic_launcher);
item.getSubMenu().setHeaderTitle("Techpalle Trainings");
Toast.makeText(getApplicationContext(), "Trainings", 0).show();
break;
case R.id.item4:
Toast.makeText(getApplicationContext(), item.getTitle(),
0).show();
break;
case R.id.item5:
item.setChecked(!item.isChecked());
Toast.makeText(getApplicationContext(), "Android", 0).show();
break;
case R.id.item6:
Toast.makeText(getApplicationContext(), "DotNet", 0).show();
break;
}
return super.onOptionsItemSelected(item);
}

}




xml layout file for First Activity 
File name: activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >


options menu file in res -> menu folder
optionsmenu.xml (in res-menu folder)
  




android:checkable="true" android:checked="true"/>
android:checkable="true"/>










context menu file in res -> menu folder
contextmenu.xml (in res-menu folder)
  





Download complete code : Click to download

Similar programs:
android Dialogs tutorial

Tags: android, tutorial, examples, menus, options menu, sub menu, context menu

Starting second activity based on login and password details: Android tutorial

Program description:

Starting second activity based on the login and password credentials given in first activity.

First activity will have 2 edit texts and 1 button. User will be prompted to enter user name in edit text1, and enter password in edit text2.

if user id is "techpalle" and password is"1234", then it will start second activity and pass the uid entered by user to second screen using explicit intent.

If user enters user id, and password wrong, then a toast message will be displayed, content of edit text 1 and edit text 2 will be cleared and automatically control will be moved to edit text1 to make user comfortable.


Once second activity is started, it takes the data passed from first activity and displays in a text view. This data passing between activities will be done by using putExtra() method.


Note: If user fails to enter user name or password correctly for 3 times, then main activity will be closed by using finish() method.


First Activity                                       First Activity (when pw is wrong)

 

First Activity (when pw is correct)          Second Activity

 


First Activity 
package com.techpalle.b15_assignment;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText e,f;
Button b;
TextView tv;
Integer cnt = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e = (EditText) findViewById(R.id.editText1);
f = (EditText) findViewById(R.id.editText2);
b = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
tv.setText(tv.getText().toString()+ cnt.toString());

b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String uid = e.getText().toString();
String pw = f.getText().toString();
boolean bu = uid.equals("techpalle");
boolean bp = pw.equals("1234");

if(bu && bp){
Intent in = new Intent(getApplicationContext(),
SecondScreen.class);
in.putExtra("uid", uid);
cnt = 0;
startActivity(in);
}else if(bu == false && bp == false){
Toast.makeText(getApplicationContext(),
"uid & pw wrong..try again", 0).show();
cnt++;
tv.setText("No of tries: "+cnt);
e.setText("");
f.setText("");
e.requestFocus();
}else if(bu == false){
Toast.makeText(getApplicationContext(),
"uid wrong..try again", 0).show();
cnt++;
e.setText("");
e.requestFocus();
tv.setText("No of tries: "+cnt);
}else{
Toast.makeText(getApplicationContext(),
"pw wrong..try again", 0).show();
cnt++;
f.setText("");
f.requestFocus();
tv.setText("No of tries: "+cnt);
}

if(cnt == 3){
Toast.makeText(getApplicationContext(),
"Tries over..", 0).show();
finish();
}
}
});
}

}


xml layout file for First Activity 
File name: activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="22dp"
android:ems="10" >


android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginLeft="14dp"
android:layout_marginTop="16dp"
android:ems="10" />



Second screen
package com.techpalle.b15_assignment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent in = getIntent();
Bundle b = in.getExtras();
String uid = b.getString("uid");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("Welcome.."+uid);
}
}
xml layout file for Second Activity 
File name: second.xml
  
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />



Download complete code : Click to download

Tags: Login page android, start activity on login, pass user id and password , android tutorial

Custom dialog to take user log in credentials: Android tutorial

Program description:

This program will show how to create a custom dialog which contains 2 edit text boxes to take log in and pass word credentials from user.


First Activity
package com.techpalle.b15_dialogassign;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
Button b;
EditText e1, e2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
b.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(1);
}
});
}

@Override
protected Dialog onCreateDialog(int id) {
Dialog d = null;
switch(id){
case 1:
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Enter user credentials");
ab.setView(getLayoutInflater().
inflate(R.layout.dialog, null));
ab.setPositiveButton("Done", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Dialog d = (Dialog) dialog;
EditText x = (EditText) d.findViewById(R.id.editText1);
EditText y = (EditText) d.findViewById(R.id.editText2);
e1.setText(x.getText().toString());
e2.setText(y.getText().toString());
}
});
d = ab.create();
break;
}
return d;
}

}
xml layout file for First Activity 
File name: activity_main.xml

  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toRightOf="@+id/textView1"
android:ems="10" >


android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText1"
android:ems="10" />



custom xml layout file for Dialog to show log in and password.
File name: dialog.xml

  
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >


android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />



Download complete code : Click to download

More  programs on dialogs:
android Dialogs(alert dialog, datepicker dialog, time picker dialog, progress dialog) tutorial

Tags: android, tutorial, examples, Custom dialog, login dialog, user input dialog

Simple calculator program to add and subtract 2 numbers: Android tutorial

Program description:

This is a simple android calculator program with 3 edit text boxes, with 2 buttons.
User will enter two numbers in first and second edit text, and click the button.
button 1 is to add two numbers, and button 2 is to subtract the numbers.

             First Activity                         First Activity( after entering numbers)


             
     First Activity( click add)                                 First Activity( click sub)




First Activity
package com.example.b15_calc;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
//step1 : create all the variables.
EditText et1, et2, et3;
Button b1, b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//step2 : get all the views from xml file.
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);

b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);

//step3 : write add functionality.
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = et1.getText().toString();
int i = Integer.parseInt(f);
String s = et2.getText().toString();
int j = Integer.parseInt(s);

Integer result = i+j;
String res = result.toString();
et3.setText(res);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = et1.getText().toString();
int i = Integer.parseInt(f);
String s = et2.getText().toString();
int j = Integer.parseInt(s);

Integer result = i-j;
String res = result.toString();
et3.setText(res);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}



xml layout file for First Activity 
File name: activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:ems="10"
android:inputType="textNoSuggestions"/>
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:ems="10" />


Download complete code : Click to download

Using alarms : Android tutorial

Program description:

This program will demo how to create alarms with broadcast receiver.

This program has one activity and one static broadcast receiver. Activity has a button, on clicking that we will set an alarm which will expire after 5 seconds from now. Once alarm is triggered it will send a broadcast with action "com.techpalle.action.ALARM_RECEIVER".
Once broadcast receiver is triggered, it will show a toast message "alarm tirggered".

In order to send a broadcast by using alarms, here we will use pending intents.

Pending intent: It is used to perform intent operations at future point of time on our behalf by some one else (mostly by alarm manager or notification manager).

Broadcast will be send after 5 seconds from the time of button click. It will be send by alarm manager. Since we are not sending broadcast immediately, and it is sent after 5 seconds. So our intent to send broadcast will be pending till then. That's why it is called as pending intent.

Steps to do this alarm program with broadcast receiver in android:
1. Create a broadcast receiver that will be triggered/ called after 5 seconds.
2. Come to activity java file, Create alarm manager object by using getSystemService() method.
3. Create intent to send a broadcast.
4. Create pending intent to shoot a broadcast from above created intent.
5. set the alarm for next 5 seconds by using alarm manager and pass pending intent.

First Activity:

package com.techpalle.b15_alarms;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button b;
AlarmManager am;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
//step1 : create alarm manager
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//a. create intent
Intent in = new Intent();
in.setAction("com.techpalle.action.ALARM_RECEIVER");
//b. create pending intent
PendingIntent pi = PendingIntent.getBroadcast(
getApplicationContext(),
0,
in,
0);
//c. set alarm for 5 seconds.
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()+5000,
pi);


}
});
}
}

Broadcast receiver 
File name : AlarmRecvr.java

package com.techpalle.b15_alarms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmRecvr extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Got the alarm..", 0).show();
}
}

xml file for first activity 
File name : activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

Manifest file
File name : AndroidManifest.xml
  
package="com.techpalle.b15_alarms"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_alarms.MainActivity"
android:label="@string/app_name" >













Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?

Sticky broadcast receiver assignment: android tutorial

Program description:

This is an assignment program on using sticky broadcast receiver. This assignment has 2 applications. 

First application will be having one activity with one button. This activity also has a dynamic receiver which will be registered on clicking that button. 
Second application is also having one activity with one button. A sticky broadcast will be fired on clicking that button.

First user will open second application and clicks on the button to send a sticky broadcast to send a broadcast with action "com.techpalle.action.STICKY".

Then user will open first application's activity and click the button to register for receiver for an action "com.techpalle.action.STICKY". Once user clicks on the button to register dynamic receiver with an action which was previously broadcasted by second application, android will immediately call the onReceive() method of the current application's dynamic receiver. Reason for this is, sticky broadcasts will stick with android for future users.

Wanted to know more about what exactly is a sticky broadcast?

First Application's First activity:

package com.techpalle.b15_rcvr_asg1;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Triggered..", 0).show();
}
};
private IntentFilter inf;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inf = new IntentFilter();
inf.addAction("com.techpalle.action.STICKY");

b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
registerReceiver(br, inf);
}
});
}

@Override
protected void onDestroy() {
unregisterReceiver(br);
super.onDestroy();
}

}

xml file for first activity 
File name : activity_main.xml

  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

Manifest file
File name : AndroidManifest.xml

  
package="com.techpalle.b15_rcvr_asg1"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_rcvr_asg1.MainActivity"
android:label="@string/app_name" >








Second Application's First activity:

package com.techpalle.b15_rcvr_asg1_app2;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent();
in.setAction("com.techpalle.action.STICKY");
sendStickyBroadcast(in);
}
});
}

}

xml file for first activity (second application)
File name : activity_main.xml

  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

Manifest file (for second application)
File name : AndroidManifest.xml

  
package="com.techpalle.b15_rcvr_asg1_app2"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_rcvr_asg1_app2.MainActivity"
android:label="@string/app_name" >









Download complete code : Click to download

Android Interview questions related to Sticky broadcast receivers:
Difference between broadcast, sendorderedbroadcast, and sendstickybroadcast?
How to send battery low broadcast?
Difference between Intent, Sticky Intent, and Pending Intent?

Tags: android, sticky broadcast, receivers, sticky, dynamic receivers, sticky intent, permission, BROADCAST_STICKY.

Dynamic receivers: android tutorial

Program description:

This is a sample demo program for dynamic receivers in Android.

This program has an activity with 2 buttons. This activity has a dynamic broadcast receiver created in it.
On clicking first button we will send a broadcast with action "DYNAMIC_RECEIVER".
On clicking second button we will register dynamic receiver with an intent filter that has action "DYNAMIC_RECEIVER".

First Activity:

package com.techpalle.b15_dyn_receivers;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
Button b1, b2;

//step1 : create a dynamic b.c.receiver in java code
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Dyn receiver triggered", 0).show();
}
};
//step2 : create intent filter
private IntentFilter inf;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1); //sending b.c
b2 = (Button) findViewById(R.id.button2); //register receiver

//prepare intent filter by adding the action.
inf = new IntentFilter();
inf.addAction("DYNAMIC_RECEIVER");

b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent();
in.setAction("DYNAMIC_RECEIVER");
sendBroadcast(in);
}
});

//step3 : register brodacast receiver with intent filter
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
registerReceiver(br, inf);
}
});
}
}

xml file for first activity 
File name : activity_main.xml

  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

Manifest file
File name : AndroidManifest.xml
  
package="com.techpalle.b15_dyn_receivers"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_dyn_receivers.MainActivity"
android:label="@string/app_name" >








Download complete code : Click to download

Android interview questions on dynamic broadcast receivers:
How to create broadcast receiver with out using manifest file?
How to start a receiver only if the application is running?

Tags: android, dynamic receivers, register receiver, button click

Spinner example with city names: Android tutorial

Program description:

This is a spinner example program which displays list of cities in it. By default it displays first city.


Spinner : Spinner is an adapter view, which displays vertically scrollable list of items displaying only one at a time in collapsed mode. When user clicks on spinner, it displays all items in expanded mode, on clicking any of the item spinner is collapsed and displays selected item.


Steps for this program:

1. Insert all cities into an array list of strings.
2. Prepare array adapter which takes elements from array list.
3. Establish communication between adapter and spinner, to allow array adapter to push elements into spinner.

First activity 


package com.techpalle.b15_spinner;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {
Spinner s;
ArrayList al;
ArrayAdapter aa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s = (Spinner) findViewById(R.id.spinner1);
al = new ArrayList();
al.add("Bangalore");
al.add("Chennai");
al.add("Hyderabad");
al.add("Delhi");

aa = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, al);
s.setAdapter(aa);
}
}

xml file for first activity 
File name : activity_main.xml


  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />


Download complete code : Click to download

Tags: android, spinner, cities

Repeating alarms with irregular intervals : Android tutorial

Program description:

This program will demo how to create alarms which will repeat at irregular intervals.

This program has one activity with one button, and a broadcast receiver.
On clicking the button, we will set an alarm for next 1 second, which triggers broadcast receiver.
Our program aim is to repeat next alarm at 2 seconds, next at 4 seconds, next at 8 seconds and so on.. For this requirement we can't use setRepeating() function of alarm manager.
We have to set the alarm manually in the receiver.

Once the first alarm (which was set for 1 second) is triggered, it will call broadcast receiver. In the receiver set alarm for next 2 seconds from that time. Which will again call same broadcast receiver after 2 seconds. Again set one more alarm for next 4 seconds in that receiver. For this we have to write a generic logic, because alarm has to repeat for n number of times.

First Activity:


package com.techpalle.b15_alarm_asg2;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
AlarmManager am;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent();
in.setAction("com.techpalle.action.ALARM_INDEF");
int i=1;
in.putExtra("val", i);
PendingIntent pi = PendingIntent.getBroadcast(
getApplicationContext(),
0,
in,
0);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()+1000,
pi);

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}

}

Broadcast receiver 
File name : AlarmRecvr.java


package com.techpalle.b15_alarm_asg2;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.ViewDebug.FlagToString;
import android.widget.Toast;

public class AlarmRecvr extends BroadcastReceiver {
//public static int i = 1;
@Override
public void onReceive(Context context, Intent intent) {
int i = intent.getExtras().getInt("val");
i = i*2;
Toast.makeText(context, "Got", 0).show();
Intent in = new Intent();
in.setAction("com.techpalle.action.ALARM_INDEF");
in.putExtra("val", i);
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()+(i*1000),
pi);
}
}

xml file for first activity 
File name : activity_main.xml
  xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

Manifest file
File name : AndroidManifest.xml

  
package="com.techpalle.b15_alarm_asg2"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.techpalle.b15_alarm_asg2.MainActivity"
android:label="@string/app_name" >













Download complete code : Click to download

Android interview questions on Power manager and wake locks:
What is sleep mode? What will happen to CPU when LCD is turned off?
What are the two components that runs in Sleep mode also?
Every day night at 12 o clock I need to post some images to Facebook, in that case I will set repeating alarm for every day night 12 am. But to upload images I want to start service, how should I do this ?
What is the difference between Intent, Sticky Intent, and Pending Intent?

Older Posts Home