Feb 20, 2013

Implement vertical ProgressBar

Vertical ProgressBar
Vertical ProgressBar

To implement custom vertical ProgressBar, create file /res/drawable/verticalprogressbar.xml to define our progressDrawable.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@android:id/background">
     <shape>
         <corners android:radius="5dip"/>
         <solid android:color="#FFFFFF"/>
         <stroke
             android:width="1dp"
             android:color="#FF000000" />
     </shape>
 </item>
 <item android:id="@android:id/progress">
     <clip
         android:clipOrientation="vertical"
         android:gravity="bottom">
         <shape>
             <corners android:radius="5dip"/>
             <solid android:color="#FFBE00"/>
             <stroke
                 android:width="1dp"
                 android:color="#FF000000" />
         </shape>
     </clip>
 </item>
</layer-list>


Modify layout to include ProgressBar with android:progressDrawable="@drawable/verticalprogressbar".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <ProgressBar 
        android:id="@+id/vprogressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" 
        android:progressDrawable="@drawable/verticalprogressbar"/>
    
    <Button
        android:id="@+id/start"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="- Start -" />

</LinearLayout>


Modify MainActivity.java to implement our AsyncTask to update the progress bar.
package com.example.androidverticalprogressbar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
 
 Button buttonStart;
 ProgressBar vProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonStart = (Button)findViewById(R.id.start);
        vProgressBar = (ProgressBar)findViewById(R.id.vprogressbar);
        
        buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    buttonStart.setClickable(false);
       new asyncTaskUpdateProgress().execute();
   }});
        
    }

    public class asyncTaskUpdateProgress extends AsyncTask<Void, Integer, Void> {

     int progress;

  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   buttonStart.setClickable(true);
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   progress = 0;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   // TODO Auto-generated method stub
   vProgressBar.setProgress(values[0]);
  }

  @Override
  protected Void doInBackground(Void... arg0) {
   // TODO Auto-generated method stub
   while(progress<100){
    progress++;
    publishProgress(progress);
    SystemClock.sleep(100);  
   }
   return null;
  }
     
    }
    
}


Related:


Feb 17, 2013

Get width and height of View in OnGlobalLayoutListener()

As you know, to get dimension of any View, you can call its getWidth() and getHeight() methoda. But it's not valid when its has not been laid out yet, such as in onCreate(). In order to read dimension when the layout ready, you can implement your OnGlobalLayoutListener, and register it by calling View.getViewTreeObserver().addOnGlobalLayoutListener().

Example:

Get width and height of View in OnGlobalLayoutListener()
Get width and height of View in OnGlobalLayoutListener()


package com.example.androidongloballayoutlistener;

import android.os.Bundle;
import android.app.Activity;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 LinearLayout mainLayout;
 TextView displayBefore, displayAfter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
        displayBefore = (TextView)findViewById(R.id.displaybefore);
        displayAfter = (TextView)findViewById(R.id.displayafter);
        
        displayBefore.setText(String.valueOf(mainLayout.getWidth()) + 
          " : " + String.valueOf(mainLayout.getHeight()));
        
        mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(myOnGlobalLayoutListener);
    }

    OnGlobalLayoutListener myOnGlobalLayoutListener =
      new OnGlobalLayoutListener(){

    @Override
    public void onGlobalLayout() {
           displayAfter.setText(String.valueOf(mainLayout.getWidth()) + 
             " : " + String.valueOf(mainLayout.getHeight()));

    }
     
    };
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" 
    android:id="@+id/mainlayout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View size onCreate()" />
    <TextView
        android:id="@+id/displaybefore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View size at OnGlobalLayoutListener()" />
    <TextView
        android:id="@+id/displayafter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


Feb 11, 2013

Detect device orientation by gravity sensor

The code demonstrate how to detect device orientation, face-up/face-down, base on gravity sensor data.

Detect device orientation by gravity sensor
Detect device orientation by gravity sensor


We can determine the device orientation(face-up or face-down) from Z value of Gravity sensor. The constant SensorManager.STANDARD_GRAVITY store the value 9.80665, it's the standard gravity (g) on Earth, equivalent to 1G. We can compare Z value with it to determine device orientation.

The code register SensorEventListener for Sensor.TYPE_GRAVITY in onResume() callback method. Once Gravity Sensor changed, the Z value can be retrieved from event.values[2].
Example code:
package com.example.androidgravitysensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;

public class MainActivity extends Activity implements SensorEventListener{
 
 private SensorManager mySensorManager;
 private Sensor myGravitySensor;
 
 TextView textFace, textZValue, textStandardGravity, textThreshold;
 
 float standardGravity;
 float thresholdGraqvity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textFace = (TextView)findViewById(R.id.face);
        textZValue = (TextView)findViewById(R.id.zvalue);
        textStandardGravity = (TextView)findViewById(R.id.standardgravity);
        textThreshold = (TextView)findViewById(R.id.threshold);
        
        standardGravity = SensorManager.STANDARD_GRAVITY;
        thresholdGraqvity = standardGravity/2;
        
        textFace.setText("");
        textZValue.setText("");
        textStandardGravity.setText("Standard Gravity = " + standardGravity);
        textThreshold.setText("Threshold = " + thresholdGraqvity);
        
        mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        myGravitySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        

    }

 @Override
 public void onAccuracyChanged(Sensor arg0, int arg1) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void onSensorChanged(SensorEvent event) {
  Sensor source = event.sensor;
  float z = event.values[2];
  
  if(source.getType() == Sensor.TYPE_GRAVITY){
   
   textZValue.setText("Z value = " + z);
   
   if (z >= thresholdGraqvity){
    textFace.setText("Face UP");
   }else if(z <= -thresholdGraqvity){
    textFace.setText("Face DOWN");
   }else{
    textFace.setText("");
   }
  }
  
 }

 @Override
 protected void onPause() {
  super.onPause();
  mySensorManager.unregisterListener(this);
  
 }

 @Override
 protected void onResume() {
  super.onResume();
  mySensorManager.registerListener(
    this, 
    myGravitySensor, 
    SensorManager.SENSOR_DELAY_NORMAL);
 }

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <TextView
        android:id="@+id/face"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/zvalue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/standardgravity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/threshold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


Related article: Get details of gravity sensor

Feb 10, 2013

Get details of gravity sensor

To list installed gravity sensor, call getDefaultSensor() of SensorManager instance, with Sensor.TYPE_GRAVITY which introduced in API level 9. What it return is a List of Sensor, with details of the associated sensor.

package com.example.androidgravitysensor;

import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;

public class MainActivity extends ListActivity {
 
 private SensorManager mySensorManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        if (mySensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null){
         List<Sensor> gravitySensorList = mySensorManager.getSensorList(Sensor.TYPE_GRAVITY);
         
         setListAdapter(new ArrayAdapter<Sensor>(
           this, 
           android.R.layout.simple_list_item_1, 
           gravitySensorList));
         
        }else{
         Toast.makeText(getApplicationContext(), "No Gravity Sensor!", Toast.LENGTH_LONG).show();
        }
    }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  Sensor sensor = (Sensor)l.getItemAtPosition(position);
  
  AlertDialog.Builder sensorDialog = new AlertDialog.Builder(MainActivity.this);
  sensorDialog.setTitle(sensor.getName());

  Class<Sensor> sensorClass = (Class<Sensor>)sensor.getClass();
  String vendor = sensor.getVendor();
  int version = sensor.getVersion();
  int type = sensor.getType();
  int minDelay = sensor.getMinDelay();
  float power = sensor.getPower();
  float maxRange = sensor.getMaximumRange();
  float resolution = sensor.getResolution();
  
  LinearLayout dialogLayout = new LinearLayout(getApplicationContext());
  LayoutParams dialogLayoutParams = new LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
  dialogLayout.setLayoutParams(dialogLayoutParams);
  dialogLayout.setOrientation(LinearLayout.VERTICAL);
  
  TextView textSensorClass = new TextView(getApplicationContext());
  textSensorClass.setText(sensorClass.toString());
  TextView textVendor = new TextView(getApplicationContext());
  textVendor.setText("Vendor: " + vendor);
  TextView textVersion = new TextView(getApplicationContext());
  textVersion.setText("Version: " + String.valueOf(version));
  TextView textType = new TextView(getApplicationContext());
  textType.setText("Type: " + String.valueOf(type));
  TextView textMinDelay = new TextView(getApplicationContext());
  textMinDelay.setText("MinDelay: " + String.valueOf(minDelay) + " microsecond");
  TextView textPower = new TextView(getApplicationContext());
  textPower.setText("Power: " + String.valueOf(power) + " mA");
  TextView textMaxRange = new TextView(getApplicationContext());
  textMaxRange.setText("MaximumRange: " + String.valueOf(maxRange));
  TextView textResolution = new TextView(getApplicationContext());
  textResolution.setText("Resolution: " + String.valueOf(resolution));
  
  dialogLayout.addView(textSensorClass);
  dialogLayout.addView(textVendor);
  dialogLayout.addView(textVersion);
  dialogLayout.addView(textType);
  dialogLayout.addView(textMinDelay);
  dialogLayout.addView(textPower);
  dialogLayout.addView(textMaxRange);
  dialogLayout.addView(textResolution);
  
  ScrollView scrollView = new ScrollView(getApplicationContext());
  LayoutParams scrollViewLayoutParams = new LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
  scrollView.setLayoutParams(scrollViewLayoutParams);
  scrollView.addView(dialogLayout);
       
  sensorDialog.setView(scrollView);
  sensorDialog.show();
 }

}


Get details of gravity sensor
details of gravity sensor


Related article: Detect device orientation by gravity sensor

Feb 9, 2013

startActivity from ResolveInfo details

Last example describe how to "Get application details via ResolveInfo". According to the retrieved ResolveInfo, we can start activity specified in Intent.

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.setClassName(packageName, name);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
      Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    startActivity(intent);


startActivity from ResolveInfo details
startActivity from ResolveInfo details


Full code:
package com.example.androidlistapps;

import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> intentList = getPackageManager().queryIntentActivities(intent, 0);
        
        setListAdapter(new ArrayAdapter<ResolveInfo>(
          this, 
          android.R.layout.simple_list_item_1, 
          intentList));
        
        Toast.makeText(getApplicationContext(), 
          "no of activities: " + intentList.size(), 
          Toast.LENGTH_LONG).show();
    }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  
  PackageManager packageManager = getPackageManager();
  ResolveInfo resolveInfo = (ResolveInfo)l.getItemAtPosition(position);
  ActivityInfo activityInfo = resolveInfo.activityInfo;

  AlertDialog.Builder appInfoDialog = new AlertDialog.Builder(MainActivity.this);
  
  CharSequence label = resolveInfo.loadLabel(packageManager);
  appInfoDialog.setTitle(label);
  
  //load icon
  ImageView icon = new ImageView(getApplicationContext());
     icon.setImageDrawable(resolveInfo.loadIcon(packageManager));
     LayoutParams iconLayoutParams = new LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
     icon.setLayoutParams(iconLayoutParams);
     
     //load package and class name
  final String name = activityInfo.name;
  final String packageName = activityInfo.applicationInfo.packageName;
  final String className = activityInfo.applicationInfo.className;
  TextView textName = new TextView(getApplicationContext());
  textName.setText("Name: " + name);
  TextView textPackageName = new TextView(getApplicationContext());
  textPackageName.setText("PackageName: " + packageName);
  TextView textClassName = new TextView(getApplicationContext());
  textClassName.setText("ClassName: " + className);
     
     LinearLayout dialogLayout = new LinearLayout(getApplicationContext());
     LayoutParams dialogLayoutParams = new LayoutParams(
       LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
     dialogLayout.setLayoutParams(dialogLayoutParams);
     
     dialogLayout.setOrientation(LinearLayout.VERTICAL);
     dialogLayout.addView(icon);
     dialogLayout.addView(textName);
     dialogLayout.addView(textPackageName);
     dialogLayout.addView(textClassName);
     
     ScrollView scrollView = new ScrollView(getApplicationContext());
     LayoutParams scrollViewLayoutParams = new LayoutParams(
       LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
     scrollView.setLayoutParams(scrollViewLayoutParams);
     scrollView.addView(dialogLayout);
     
     appInfoDialog.setView(scrollView);
         
     appInfoDialog.setNegativeButton("Cancel", null);
     appInfoDialog.setPositiveButton("Start App", 
       new DialogInterface.OnClickListener() {
   
   @Override
   public void onClick(DialogInterface dialog, int which) {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.setClassName(packageName, name);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
      Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    startActivity(intent);
    
   }
  });
     appInfoDialog.show();
  
 }
}


Feb 8, 2013

Get application details via ResolveInfo

Via ResolveInfo return from PackageManager.queryIntentActivities(), we can get details of the application. This example demonstarte how to get Label, Icon, name, packageName and className.

Get application details via ResolveInfo


package com.example.androidlistapps;

import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> intentList = getPackageManager().queryIntentActivities(intent, 0);
        
        setListAdapter(new ArrayAdapter<ResolveInfo>(
          this, 
          android.R.layout.simple_list_item_1, 
          intentList));
        
        Toast.makeText(getApplicationContext(), 
          "no of activities: " + intentList.size(), 
          Toast.LENGTH_LONG).show();
    }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  
  PackageManager packageManager = getPackageManager();
  ResolveInfo resolveInfo = (ResolveInfo)l.getItemAtPosition(position);
  ActivityInfo activityInfo = resolveInfo.activityInfo;

  AlertDialog.Builder appInfoDialog = new AlertDialog.Builder(MainActivity.this);
  
  CharSequence label = resolveInfo.loadLabel(packageManager);
  appInfoDialog.setTitle(label);
  
  //load icon
  ImageView icon = new ImageView(getApplicationContext());
     icon.setImageDrawable(resolveInfo.loadIcon(packageManager));
     LayoutParams iconLayoutParams = new LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
     icon.setLayoutParams(iconLayoutParams);
     
     //load package and class name
  String name = activityInfo.name;
  String packageName = activityInfo.applicationInfo.packageName;
  String className = activityInfo.applicationInfo.className;
  TextView textName = new TextView(getApplicationContext());
  textName.setText("Name: " + name);
  TextView textPackageName = new TextView(getApplicationContext());
  textPackageName.setText("PackageName: " + packageName);
  TextView textClassName = new TextView(getApplicationContext());
  textClassName.setText("ClassName: " + className);
     
     LinearLayout dialogLayout = new LinearLayout(getApplicationContext());
     LayoutParams dialogLayoutParams = new LayoutParams(
       LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
     dialogLayout.setLayoutParams(dialogLayoutParams);
     
     dialogLayout.setOrientation(LinearLayout.VERTICAL);
     dialogLayout.addView(icon);
     dialogLayout.addView(textName);
     dialogLayout.addView(textPackageName);
     dialogLayout.addView(textClassName);
     
     ScrollView scrollView = new ScrollView(getApplicationContext());
     LayoutParams scrollViewLayoutParams = new LayoutParams(
       LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
     scrollView.setLayoutParams(scrollViewLayoutParams);
     scrollView.addView(dialogLayout);
     
     appInfoDialog.setView(scrollView);
         
     appInfoDialog.setPositiveButton("OK", null);
     appInfoDialog.show();
  
 }
}


Next: startActivity from ResolveInfo details


Feb 6, 2013

List all installed activities

We can list all activities that can be performed for the given intent by calling PackageManager.queryIntentActivities(Intent intent, int flags).

List all installed activities


package com.example.androidlistapps;

import java.util.List;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ResolveInfo;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> intentList = getPackageManager().queryIntentActivities(intent, 0);
        
        setListAdapter(new ArrayAdapter<ResolveInfo>(
          this, 
          android.R.layout.simple_list_item_1, 
          intentList));
        
        Toast.makeText(getApplicationContext(), 
          "no of activities: " + intentList.size(), 
          Toast.LENGTH_LONG).show();
    }

}


Next: Get application details via ResolveInfo


Feb 4, 2013

Implement callback method

In this example, demonstrate how to implement callback method in Android. The main activity implements interface of callback method, and register itself as the interface to sub-class. When a button in main activity clicked, it call a method in sub-class, then call the callback method in main activity.

SubClass.java
package com.example.androidcallback;

public class SubClass {
 
 interface MyCallbackClass{
        void callbackReturn();
    }
 
 MyCallbackClass myCallbackClass;
 
 void registerCallback(MyCallbackClass callbackClass){
  myCallbackClass = callbackClass;
 }

 void doSomething(){
  //do something here
  
  //call callback method
  myCallbackClass.callbackReturn();
 }

}


MainActivity.java
package com.example.androidcallback;

import com.example.androidcallback.SubClass.MyCallbackClass;

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

public class MainActivity extends Activity implements MyCallbackClass{
 
 Button buttonCallSubClass;
 TextView textResult;
 SubClass mySubClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonCallSubClass = (Button)findViewById(R.id.callsubclass);
        textResult = (TextView)findViewById(R.id.result);
        
        mySubClass = new SubClass();
        
        mySubClass.registerCallback(this);
        
        buttonCallSubClass.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    mySubClass.doSomething();
   }});
    }

 @Override
 public void callbackReturn() {
  textResult.setText("Callback function called");
 }
   
}


layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/callsubclass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call sub-class" />
    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Implement callback method

Infolinks In Text Ads