Open top menu

                             
                                             Android Toast Example 

               
 Toast notify the user about an operation without expecting any input. Toast provided the  small popup take few seconds and automatically fade out.

For example,  The Toast notify the click on button "press a left button",  show after click on button, popup 

in same activity .
Instantiate a android.widget.Toast object   using  static  makeText();     method. this method take a three parameters  application  Context,  the  text  message, and  the  duration  for  the Toast.
Toast notification  by calling  show (); method.


//display in short period of time
Toast.makeText(getApplicationContext(), "press a left button",
                      Toast.LENGTH_SHORT).show();
 String data="press a left button";
//display data value
Toast.makeText(getApplicationContext(), data,
                        Toast.LENGTH_SHORT).show(); 
Read more


 How to pass data from one activity to another in android ?

 Android user interface is show through an activity. Activity is used to represent the  user information and allows user interaction.  During activity interaction we might required to transfer data from one activity to other activity. i have explain in briefly-  

* how to activity interact via intent ? explain
   pass the value via intent object,
   intent.putExtera("key name","your value");
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  String message=" Help me";
  
  Intent intent=new Intent(MainActivity.this,AnotherActivity.class);
  
  //intent.putExtra(< put your key name>, <your passing value>);
  
  intent.putExtra("data", message);
  startActivity(intent);
  
  
 }
 

}
you can retrieve the value via getIntent(); method on intent object;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class AnotherActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.anotheracitvity);
       //get string value
  Intent intent=getIntent();
  String message= intent.getStringExtra("data");
  
  
  
 }

}

Read more

How to implement Notification in android?


Let’s now take a peek at the Notification sample project,




How to implement Notification in android?
 about this tree structure i have created One Activity And two services class,shown below
MainActivity.java

package com.example.notification;

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

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStartService = (Button)findViewById(R.id.start_Myservice);
        Button buttonStopService = (Button)findViewById(R.id.stop_Myservice);
        
        buttonStartService.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NotificationsService.class);
MainActivity.this.startService(intent);
}});
        
        buttonStopService.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(NotificationsService.ACTION);
intent.putExtra("SERVICE", NotificationsService.STOP_SERVICE);
sendBroadcast(intent);
}});
        
}

@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;
}

}

You have created new Broadcast reciver class-->>>>>>>>>>

MyAction_Services.java

package com.example.notification;

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

public class MyAction_Services extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent i = new Intent(context,NotificationsService.class);
      context.getApplicationContext().startService(i);
}

}

And last Notifcation services--->>>>>>>>>>>>>>>>>>>>>>

package com.example.notification;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;

public class NotificationsService extends Service {
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int REQUIRE_STOP_SERVICE = 1;
MyAction_Services notifyServiceReceiver;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
private final String myBlog = "http://androidbeginnerpoint.blogspot.in/";
@Override
public void onCreate() {
// TODO Auto-generated method stub
notifyServiceReceiver = new MyAction_Services();
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
// Send Notification
notificationManager = 
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher, 
"Notification!", 
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Exercise of Notification!";
String notificationText = "http://android-er.blogspot.com/";
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent 
= PendingIntent.getActivity(getBaseContext(), 
0, myIntent, 
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context, 
notificationTitle, 
notificationText, 
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

public class NotifyServiceReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("SERVICE", 0);
if (rqs == REQUIRE_STOP_SERVICE){
stopSelf();
}
              }
}
}

User interface created inside res/layout/main.xml-->>>>>>>>



 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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_world"
    />
<Button
    android:id="@+id/start_Myservice"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Start Service to send Notification"
    />
<Button
    android:id="@+id/stop_Myservice"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Stop Service"
    />
</LinearLayout>

Note-you can not forget given permission in Manifest file.

<service android:name=".NotificationsService"/>
 <receiver android:name=".MyAction_Services">

---------------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notification"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.notification.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <service android:name=".NotificationsService"/>
    <receiver android:name=".MyAction_Services">
    <intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    </intent-filter>
    </receiver>
    </application>

</manifest>




Read more

 Android life cycle

Mobile device provided limited RAM; your activity may find itself being killed off because other activities are going on and the system needs your activity’s memory. Think of it as the Android equivalent of the circle of life: Your activity dies so others may live, and so on. You cannot assume that your activity will run until you think it is complete, or even until the user thinks it is complete. This is one example—perhaps the most important example—of how an activity’s life cycle will affect your own application logic. In this tutorial various states and callbacks that make up an activity’s life cycle, and how you can hook into them appropriately.

Life cycle structure

An activity generally used four states at any point in time:
·         Active: The activity was started by the user, is running, and is in the foreground. This is what you’re used to thinking of in terms of your activity’s operation.

·         Paused: The activity was started by the user, is running, and is visible, but a notification or something is overlaying part of the screen. During this time, the user can see your activity but may not be able to interact with it. For example, if you have doing a phone call via dual SIM Card  the user will get the opportunity to Both SIM  Call option SIM1 And SIM2

·         Stopped: Activity was started by the user, is running, but in a background running by other activities that have been launched. Your application will not be able to present anything meaningful to the user directly, but may communicate by way of notifications.

·         Dead: Either the activity was never started (e.g., just after a phone reset) or the activity was terminated.




  

onStart(), onRestart(), and onStop()

An activity can come to the foreground because it is first being launched, or because it is being brought back to the foreground after having been hidden, e.g., by another Activity or by an incoming phone call. The onStart() method is called.

The onRestart() method is called in the case where the activity had been stopped and is now restarting.

 onStop() is called when the activity is about to be stopped.

onPause() and onResume()

The onResume() method is called just before your activity comes to the foreground, after launched, being restarted from a stopped state, or a pop-up dialog (e.g. Battery is Low) is cleared. This is a great place to refresh the UI based on things that


Once onPause() is called, Android reserves the right to kill off your activity’s process at any point.
Read more

Font

You have to put question “hey, can we change Text font our application?” Answer is depends on which your platform comes with this font. Whether you can add other fonts, and how to apply them to the widget or whatever needs the font change?

Android natively used three font knows, of "sans", "serif", and "monospace". you have change font in  .xml class ,{ android:typeface="monospace"}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SARVESH KAUSHIK"
        android:typeface="monospace"
        android:textSize="20dp" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SARVESH KAUSHIK"
        android:typeface="sans" 
        android:textSize="20dp"/>
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SARVESH KAUSHIK"
        android:typeface="serif"
        android:textSize="20dp" /> 
</LinearLayout>







More Font

You have add more font via assets folder .The easiest way to accomplish this is to package the desired font(s) with your application.Simply create an assets/ folder in the project root, and put your True-type (TTF) fonts in that folder. You might, for example, create assets/fonts/ and put your TTF files there.

Then your widgets to use that font. Unfortunately, you can no longer use
layout XML for this, since the XML . Instead, you need to make the change in Java code:


public class Font extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

TextView tv=(TextView)findViewById(R.id.newfont);

Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}









Read more

Activity


The activity is a user interface. Your project Src / directory based upon the java package you used when you created the project (com.yourpackgename.myapp).
the root à src/packge/Myactivity.java .

package com.example.addgooglemap;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity{
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
       
 // set user interface
              setContentView(R.layout. my_activity);
       }

}

User interface inside  res/Layout/my_activity.xml.

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   


</LinearLayout>
Read more

 Project Structure


The   Android build a system Make Specific Directory tree structure for your android project, same as Java project. 
  • AndroidManifest.xml, an XML file describing the application being built and what Components—activities, services, etc.—are being supplied by that application.       
  •   build.xml, an script for compiling the application and installing it on the device default. Properties, a property file used by the  build script.
  • bin/ holds the application once it is compiled.

  •  
  •  libs/ holds any third-party Java JARs your application requires.

  • src/ holds the Java source code for the application. 
  • res/ holds resources, such as icons, GUI layouts, and the like, that get packaged with              the compiled Java in the application. 

  • assets/ holds other static files you wish packaged with the application for deployment onto the device 

Read more

How to create new android project in eclipse?


First time manage Eclipse and ADT, Android SDK.  The Android SDK show new android project create option.
1.       First open eclipse developing tool.
2.       Select file eclipse right sideàclick on New optionàSelect Android Application Projects
3.       Show screen shot



4.    Open new Android Application Window.

5.    Enter Project Name.
6.    You have to Edit Package Name.
7.    Show next Screen shot.
8.    Select  Required SDKàHighest SDKà Theam
9.    Then click on next button.





10.  Click on Nextàhow new window configure Projectànext button.

11.  Then open new Configure the attributes of the icon set window. You have to select new icon click on browser. Click on next button
12.  Then Nextà Nextà Finish



















Read more