How to connect your activity to its fragment

Standard

Often you will want one Fragment to communicate with its Activity also all Fragment-to-Fragment communication must be done through the associated Activity. Two Fragments should never communicate directly.

Define an Interface
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    
    ...
}

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface.

Implement the Interface
In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...
    
    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
    }
}

 

full version at:
http://developer.android.com/training/basics/fragments/communicating.html

Understanding Android Activity lifecycle

Standard

Usually, an Android application consists of more than one activity. These activities are loosely bounded with each other. It is a good practice to create each activity for a specific task to be performed. For example, in a simple phone dialing application, there might be one activity to show all contacts, one to show full contact details of any specific contact, one for dialing a number, and so on. In all the applications, there is a main activity that behaves as the starting point of the application. This activity starts when the application is launched. Then this activity starts some other activity, which starts another, and so on. Android manages all the activities in a back stack.

How to catch application “force closed” message?

Standard

The trick is make sure it doesn’t Force Close in the first place.

If you use the Thread.setDefaultUncaughtExceptionHandler() method you can catch the Exceptions that are causing your application to Force Close.

onCreate add:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
 @Override
 public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
 myHandaling(paramThread, paramThrowable);
 }
 });
public void myHandaling(Thread paramThread, Throwable paramThrowable){
 Log.e("Alert","Lets See if it Works !!!" +"paramThread:::" +paramThread +"paramThrowable:::" +paramThrowable);
 Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert uncaughtException111",Toast.LENGTH_LONG).show();
 Intent in =new Intent(ForceCloseExceptionHandalingActivity.this,com.satya.ForceCloseExceptionHandaling.ForceCloseExceptionHandalingActivity.class);
 startActivity(in);
 finish();
 android.os.Process.killProcess(android.os.Process.myPid()); 
 }

How to use Google Analytic for your app

Standard

Introduction

The Google Analytics SDK for Android makes it easy for developers to collect user engagement data from their apps. Developers can then use the Google Analytics app-tracking reports to measure:

  • The number of active users are using their applications.
  • From where in the world the application is being used.
  • Adoption and usage of specific features.
  • In-app purchases and transactions.
  • The number and type of application crashes.
  • And many other useful metrics.

How to make an advanced Splash Screen for your Android App

Standard

Create your splash.xml file some thing like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" 
 android:id="@+id/TheSplashLayout"
 android:layout_gravity="center"
 >
 <ImageView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:id="@+id/SplashImageView"
 android:layout_gravity="center" 
 android:src="@drawable/lnxins" 
 >
 </ImageView>
</LinearLayout>

Write your Splash screen java file:

public class SplashScreen extends Activity {
 
 /**
 * The thread to process splash screen events
 */
 private Thread mSplashThread; 

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

 // Splash screen view
 setContentView(R.layout.splash);
 
 final SplashScreen sPlashScreen = this; 
 
 // The thread to wait for splash screen events
 mSplashThread = new Thread(){
 @Override
 public void run(){
 try {
 synchronized(this){
 // Wait given period of time or exit on touch
 wait(5000);
 }
 }
 catch(InterruptedException ex){ 
 }

 finish();
 
 // Run next activity
 Intent intent = new Intent();
 intent.setClass(sPlashScreen, MainActivity.class);
 startActivity(intent);
 stop(); 
 }
 };
 
 mSplashThread.start(); 
 }
 
 /**
 * Processes splash screen touch events
 */
 @Override
 public boolean onTouchEvent(MotionEvent evt)
 {
 if(evt.getAction() == MotionEvent.ACTION_DOWN)
 {
 synchronized(mSplashThread){
 mSplashThread.notifyAll();
 }
 }
 return true;
 } 
}

Create apear and disapear animation xml files:

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <alpha
 android:interpolator="@android:anim/accelerate_interpolator"
 android:fromAlpha="0.0" android:toAlpha="1.0"
 android:duration="800"
 />
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <alpha
 android:interpolator="@android:anim/decelerate_interpolator"
 android:fromAlpha="1.0" android:toAlpha="0.0"
 android:duration="800"
 />
</set>

Add your animation as a style to your style resource file:

<style name="Animations" parent="@android:Animation" />
 <style name="Animations.SplashScreen">
 <item name="android:windowEnterAnimation">@anim/appear</item>
 <item name="android:windowExitAnimation">@anim/disappear</item> 
 </style>
</style>

Add this style to your style resource file for a transparent splash activity:

 <style name="Theme.Transparent" parent="android:Theme">
 <item name="android:windowIsTranslucent">true</item>
 <item name="android:windowBackground">@android:color/transparent</item>
 <item name="android:windowContentOverlay">@null</item>
 <item name="android:windowNoTitle">true</item>
 <item name="android:windowIsFloating">true</item>
 <item name="android:backgroundDimEnabled">false</item>
 <item name="android:windowAnimationStyle">@style/Animations.SplashScreen</item>
 </style>

Add your splash activity to manifest file like this:

<activity 
 android:name="SplashScreen"
 android:theme="@style/Theme.Transparent">
 <intent-filter>
 <action android:name="android.intent.action.MAIN"></action>
 <category android:name="android.intent.category.LAUNCHER"></category>
 </intent-filter>
</activity>

 

Splash Sample

Splash Sample

That’s it…

How to Disable or Manage Android Clear Data

Standard

You have to add this part to your manifest file:

android:manageSpaceActivity=".ActivityOfYourChoice"

and then instead of "Clear Data", there is a button for "Manage Space" which launches ActivityOfYourChoice.

Also you can make a fake activity that do nothing:

public class ActivityOfYourChoice extends Activity {

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

 finish();
 }
}

How to Hide Android Soft Keyboard

Standard

An open keyboard under your gourdes form is too annoying and takes lots of screen while you design a data entry form in an Android application. To hide soft-keyboard at your form statrup add this tag to your project manifest under activity:

android:windowSoftInputMode="stateHidden"

and it’s gone! (Don’t worry, it will come back when you click on an EditText control)