26 May 2017

Add name, icon and permissions to your phonegap app

You must have made html files including index.html file in it as shown in a previous post. Then you zip it, upload it and build it on build.phonegap.com, but the name and icon of yout app does not change. You must add config file to your app to change it. Let me show you how.

Step 1 :
The sample config.xml file can be found here. You can make changes according to your application. The config file for my app is shown below. I have included almost all the permissions for my app, but you can modify yours accordingly.
Also add the icon image (preferable png - for ios support) in the main directory (path mentioned in the config file as main directory)

config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns   = "http://www.w3.org/ns/widgets"
    xmlns:gap   = "http://phonegap.com/ns/1.0"
    id          = "com.phonegap.example"
    versionCode = "10"
    version     = "1.0.0" >

<!-- versionCode is optional and Android only -->

  <name>Stitch</name>

  <description>
     App to know hardware processes
  </description>

<preference name="Fullscreen" value="true"/>

<preference name="DisallowOverscroll" value="true"/>

<preference name="HideKeyboardFormAccessoryBar" value="false"/>

<access origin="*"/>
    <!-- Added the following intents to support the removal of whitelist code from base cordova to a plugin -->
    <!-- Whitelist configuration. Refer to https://cordova.apache.org/docs/en/edge/guide_appdev_whitelist_index.md.html -->
    <plugin name="cordova-plugin-whitelist" version="1" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />

    <platform name="android">
        <allow-intent href="market:*" />
    </platform>

    <plugin name="cordova-plugin-battery-status" />
    <plugin name="cordova-plugin-camera" />
    <plugin name="cordova-plugin-media-capture" />
    <plugin name="cordova-plugin-console" />
    <plugin name="cordova-plugin-contacts" />
    <plugin name="cordova-plugin-device" />
    <plugin name="cordova-plugin-device-motion" />
    <plugin name="cordova-plugin-device-orientation" />
    <plugin name="cordova-plugin-dialogs" />
    <plugin name="cordova-plugin-file" />
    <plugin name="cordova-plugin-file-transfer" />
    <plugin name="cordova-plugin-geolocation" />
    <plugin name="cordova-plugin-globalization" />
    <plugin name="cordova-plugin-inappbrowser" />
    <plugin name="cordova-plugin-media" />
    <plugin name="cordova-plugin-network-information" />
    <plugin name="cordova-plugin-splashscreen" />
    <plugin name="cordova-plugin-vibration" />

 
  <author href="https://build.phonegap.com" email="support@phonegap.com">
      Yatin Kode
  </author>
 
  <icon src="android.png" /> <!-- icon is saved in png format in the main directory>

</widget>

Step 2 : Add the config.xml file in the main directory of our application folder.


Step 3 : Zip the folder, upload it on build.phonegap.com and build it as shown in a previous post. The icon will appear there after it builds successfully.
Phonegap app with custom icon
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 26.5.17

4 April 2016

Make Android app to send email

What we will do ?
-> We will ask user to input recipient email id,subject and body of the email, then we will send the mail through a email service present in the mobile.

What we will need ?
  • Sample email-id, subject and message for the email
  • 3 EditText and 1 Button
  • Additions in MainActivity.java
Step 1 : Create a new application. Go to File->New->Android Application Project.
file new android app

Step 2 : Give a Name as SendEmail and package name as com.mia.sendemail to your application.Click Next continuously.
sendemail mia
Click Finish.
click finish

Step 3 : Drag 3 EditText and a Button from the Palette to activity_main layout.The code is shown below.
drag 3 edittext and 1 button
activity_main.xml
<RelativeLayout 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: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="com.mia.sendemail.MainActivity" >

    <Button
        android:id="@+id/sendbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/body"
        android:layout_marginTop="22dp"
        android:text="Send" />

    <EditText
        android:id="@+id/subject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inputemail"
        android:ems="10" />

    <EditText
        android:id="@+id/body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/subject"
        android:ems="10"
        android:inputType="textMultiLine" />

    <EditText
        android:id="@+id/inputemail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/subject"
        android:layout_alignParentTop="true"
        android:layout_marginTop="64dp"
        android:ems="10"
        android:inputType="textEmailAddress" />

</RelativeLayout>

Step 4 : Open MainActivity.java from src->com.mia.sendmail and copy the code below in it.

MainActivity.java
package com.mia.sendemail;

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

public class MainActivity extends Activity {

 EditText emailid,subject,body;
 Button sendbutton;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  emailid=(EditText) findViewById(R.id.inputemail);
  subject=(EditText) findViewById(R.id.subject);
  body=(EditText) findViewById(R.id.body);
  sendbutton=(Button) findViewById(R.id.sendbutton);
  
  sendbutton.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {   
    String contentemail = emailid.getText().toString();
      String contentsubject = subject.getText().toString();
      String contentbody = body.getText().toString();
  
      Intent email = new Intent(Intent.ACTION_SEND);
      email.putExtra(Intent.EXTRA_EMAIL, new String[]{ contentemail});
      email.putExtra(Intent.EXTRA_SUBJECT, contentsubject);
      email.putExtra(Intent.EXTRA_TEXT, contentbody);
      email.setType("message/rfc822");    
      startActivity(Intent.createChooser(email, "Choose an Email client :"));
   }}); 
 }
}

Step 5 : Run the Application
output email
output email
Explanation of the code :

Explanation from activity_main.xml :
  • We have used 3 EditText for entering email-id, subject and message of the mail.
<EditText
        android:id="@+id/subject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inputemail"
        android:ems="10" />

    <EditText
        android:id="@+id/body"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/subject"
        android:ems="10"
        android:inputType="textMultiLine" />

    <EditText
        android:id="@+id/inputemail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/subject"
        android:layout_alignParentTop="true"
        android:layout_marginTop="64dp"
        android:ems="10"
        android:inputType="textEmailAddress" />
  • Then we use a Button to send the e-mail.
<Button
        android:id="@+id/sendbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/body"
        android:layout_marginTop="22dp"
        android:text="Send" />
Explanation from MainActivity.java :
  • We assign the EditTexts and Button to their respective variables.
emailid=(EditText) findViewById(R.id.inputemail);
subject=(EditText) findViewById(R.id.subject);
body=(EditText) findViewById(R.id.body);
sendbutton=(Button) findViewById(R.id.sendbutton);
  • Under the onClick() method we convert the input from the EditTexts to String using toString() method.
String contentemail = emailid.getText().toString();
String contentsubject = subject.getText().toString();
String contentbody = body.getText().toString();
  • Then we prepare an Intent named email of ACTION_SEND is used to perform action of sending some data by using this Intent.
Intent email = new Intent(Intent.ACTION_SEND);
  • putExtra() method is used to add extra data to the Intent. We add the email-id,, subject and message to the Intent by using its respective methods. There is also a provision to add BCC to the mail.
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ contentemail});
email.putExtra(Intent.EXTRA_SUBJECT, contentsubject);
email.putExtra(Intent.EXTRA_TEXT, contentbody);
email.setType("message/rfc822");
  • setType() method is used to set the client type.[RFC822]
email.setType("message/rfc822");
  • Then we start the activity using startActivity(). "Choose an Email client" message is used to choose specific email client from those available in the mobile phone.
startActivity(Intent.createChooser(email, "Choose an Email client :"));
Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 4.4.16

10 January 2016

Make homescreen widget of android app

What we will do?
-> We will make a sample homescreen widget with text, image and button.

What we will need?
  • activity_main.xml
  • mywidget.xml
  • Changes in MainActivity.java
  • Changes in AndroidManifest.xml
Step 1 : Create a new application. Go to File->New->Android Application Project.

Step 2 : Give name as SampleWidget and package name as com.mia.samplewidget. Then click Next continuously. 
Click Finish

Step 3 : Go to activity_main.xml. Add an ImageView, TextView and Button in a RelativeLayout,

activity_main.xml 
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:background="#FFFFFF"
   android:transitionGroup="true">


   <ImageView
       android:id="@+id/imageView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true"
       android:src="@drawable/logo" />


   <TextView
       android:id="@+id/textView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/imageView1"
       android:layout_alignRight="@+id/imageView1"
       android:layout_below="@+id/imageView1"
       android:text="Made In Android"
       android:textColor="#000000"
       android:textSize="35dp" />


   <Button
       android:id="@+id/button1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/textView"
       android:layout_alignParentRight="true"
       android:layout_alignTop="@+id/imageView1"
       android:layout_marginLeft="22dp"
       android:layout_marginTop="29dp"
       android:gravity="center"
       android:background="#6E6E6E"
       android:layout_toRightOf="@+id/imageView1"
       android:text="Visit Site" />


</RelativeLayout>

Step 4 : Create a new folder in res folder. Right-click on res->New Folder and name it as xml

Step 5 : Right click on xml->Android XML File and name it as mywidget.xml.
Code for mywidget.xml is given below

mywidget.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
   xmlns:android="http://schemas.android.com/apk/res/android" 
   android:minWidth="250dp" 
   android:updatePeriodMillis="0" 
   android:minHeight="146dp" 
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

Step 6 : Open MainActivity.java from src->com.mia.samplewidget

MainActivity.java
package com.mia.samplewidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppWidgetProvider{

   public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
      for(int i=0; i<appWidgetIds.length; i++){
         int currentWidgetId = appWidgetIds[i];
         String url = "http://www.madeinandroid.net";
         
         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.setData(Uri.parse(url));
         
         PendingIntent pending = PendingIntent.getActivity(context, 0,intent, 0);
         RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.activity_main);
         
         views.setOnClickPendingIntent(R.id.button1, pending);
         appWidgetManager.updateAppWidget(currentWidgetId,views);
         Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show(); 
      }   
   }
}

Step 7 : Open AndroidMainfest.xml and alter the default code to the below code.

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
          
         <receiver android:name=".MainActivity">
      <intent-filter>
         <action android:name="android.appwidget.action.APPWIDGET_UPDATE"></action>
      </intent-filter>
      <meta-data android:name="android.appwidget.provider"
         android:resource="@xml/mywidget"></meta-data>
      </receiver>
        
    </application>

</manifest>

Step 8 : Run the application. Then go to Widgets section from your Emulator/Mobile and drag the widget to the homescreen.
Github download
Stay Tuned with Made In Android

Published By:
Sofiya Shaikh
on 10.1.16

26 November 2015

Launch system apps from your Android app

What we will do?
->We will launch default (in-built) calculator in the android app you have made.

What we will need?
  • Button in activity_main.xml
  • Emulator or mobile with default calculator
  • Changes in MainActivity.java
Step 1 : Create a new application. Go to File->New->Android Application Project.
file new android app

Step 2 : Give a Name to your application as LaunchDefault and package name as com.mia.launchdefault. Then click Next continously.
launchdefault com.mia.launchdefault
Click Finish
finish

Step 3 : Add a Button to activity_main.xml.

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="#D8D8D8"
        android:text="Calculator" />

</LinearLayout>


Step 4 : Go to MainActivity.java from src->com.mia.launchdefault. Code for MainActivity is as follows.

MainActivity.java
package com.mia.launchdefault;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
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);
  
  final Button buttonC = (Button)findViewById(R.id.button1); 
  buttonC.setOnClickListener(new Button.OnClickListener()
  {
    @Override
             public void onClick(View v) {
     Intent i = new Intent();
     i.setAction(Intent.ACTION_MAIN);
     i.addCategory(Intent.CATEGORY_APP_CALCULATOR);
     startActivity(i);
    }
  });
 
}
}

Step 5 : Run the Project.
Calculator will open as you will press the button.

Explanation of the code:

Explanation from MainActivity.java:

  • We will prepare an Intent object named i. Then we use setAction() to open the MAIN i.e. first page of the desired app.
  •  Then we use addCategory() function and add calculator using CATEGORY_APP_CALCULATOR.
  • We can also launch many other inbuild apps using the following categories.
category inbuilt apps functions
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 26.11.15

22 October 2015

Make Custom Circular progress bar with percentage in android

What we will do?
-> We will make a circle progress bar with increasing percentage in between the circle.

What we need?
  • attrs.xml
  • MainActivity.java
  • MeterView.java
  • activity_main.java
Step 1 : Create a new Project. Go to File->New->Android Application Project
file new android project

Step 2 : Give a name to your application as CircleProgress and package name as com.mia.circleprogress. Click Next continuously
circleprogress com.mia.circleprogress
Click Finish
finish

Step 3 :  Create a new xml file in res->values and name it as attrs. Right click on values folder->New->Android XML File and name it as attrs.

attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MeterViewAttr">
        <attr name="angle" format="integer" />
        <attr name="spacing" format="integer" />
        <attr name="lineWidth" format="integer" />
        <attr name="lineColor" format="color" />
        <attr name="pathColor" format="color" />
    </declare-styleable>
</resources>

Step 4 : Make a new class in src->com.mia.circleprogress. Right click on com.mia.circleprogress->New->Class and name it as MeterView.

MeterView.java
package com.mia.circleprogress;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

interface OnFinishListener {
 public void onFinish();
}

public class MeterView extends View implements Runnable {
 
 private int angle = 0, spacing = 0, lineWidth = 0;
 private int lineColor = 0, pathColor = 0;
 private boolean runasync = true, count = false, done = false;
 private int start = 0, stop;
 private int interval = 1000, value = 0, total = 1;
 private Thread thread = new Thread(this);
 private Handler handler = new Handler();
 private OnFinishListener f = new OnFinishListener() {
  public void onFinish() { }
 };
 
 public MeterView(Context context) {
  super(context);
 }
 
 public MeterView(Context context, AttributeSet attributes) {

//store values from attrs.xml in TypedArray a
  super(context, attributes);
  TypedArray a = context.obtainStyledAttributes(attributes, R.styleable.MeterViewAttr);
  this.angle = a.getInteger(R.styleable.MeterViewAttr_angle, 0);
  this.spacing = a.getInteger(R.styleable.MeterViewAttr_spacing, 0);
  this.lineWidth = a.getInteger(R.styleable.MeterViewAttr_lineWidth, 0);
  this.lineColor = a.getInteger(R.styleable.MeterViewAttr_lineColor, 0);
  this.pathColor = a.getInteger(R.styleable.MeterViewAttr_pathColor, 0);
  a.recycle();
 }
 
 public void runAsync(boolean runasync) {
  this.runasync = runasync;
 }
 
 public void setValue(int value, int total) {
  this.angle = (value * 360) / total;                        //angle at any instance
  this.invalidate();
 }
 
 public int getValue() {  return this.angle; }
 
 public void onDraw(Canvas canvas) {
  int width = this.getWidth();                                               //width of screen
  int height = this.getHeight();                                             //height of screen
  int minLength = (width < height) ? width : height;
  int textSize = minLength / 4;                                             //size of number percentage
  
  int left = (width > minLength) ?  spacing + (width - minLength) / 2 : spacing;
  int top = (height > minLength) ? spacing + (height - minLength) / 2 : spacing;
  int right = (width > minLength) ? width - left : minLength - left;
  int bottom = (height > minLength) ? height - top : minLength - top;
  
  Paint p = new Paint();
  p.setTextSize(textSize);
  p.setStrokeWidth(lineWidth);
  p.setAntiAlias(true);
  p.setStyle(Paint.Style.STROKE);
  p.setTextAlign(Paint.Align.CENTER);
  
  RectF area = new RectF(left, top, right, bottom);           //rectangle whose all sides are tangent to the circle
  
  // Draw path
  p.setColor(pathColor);
  canvas.drawArc(area, -90, 360, false, p);
  
  // Draw actual value
  p.setColor(lineColor);
  canvas.drawArc(area, -90, angle, false, p);
  
  int offsetX = getWidth() / 2;
  int offsetY = (getHeight() - ((int) p.ascent() + (int) p.descent())) / 2;
  int num = (angle * 100) / 360;
  String value = (num == 0 || num == 100) ? String.valueOf("") : String.valueOf(num);
  p.setStyle(Paint.Style.FILL);
  if(minLength >= textSize || !value.matches("0") || !value.matches("100"))
   canvas.drawText(value, offsetX, offsetY, p);
  
  if(num >= 100 && !this.runasync) {
   this.setValue(0, 1);
   this.f.onFinish();
  }
 }
 
 public int hex2rgb(String hex) {
  int r = (hex.length() < 6) ? Integer.valueOf(hex.substring(1, 2) + hex.substring(1, 2), 16) : Integer.valueOf(hex.substring(1, 3), 16);
  int g = (hex.length() < 6) ? Integer.valueOf(hex.substring(2, 3) + hex.substring(2, 3), 16) : Integer.valueOf(hex.substring(3, 5), 16);
  int b = (hex.length() < 6) ? Integer.valueOf(hex.substring(3, 4) + hex.substring(3, 4), 16) : Integer.valueOf(hex.substring(5, 7), 16);
  return Color.rgb(r, g, b);
 }
 
 public void run() {                //run thread to count value at each instance
  while (this.runasync) {
   try {
    if (this.count) this.value += 1;
    
    if (this.value >= this.total) {
     this.count = false;
     this.done = true;
    }
    
    if (this.done) {
     this.handler.post(new Runnable() {
      public void run() {
       value = start;
       total = stop;
       f.onFinish();
      }
     });
     this.done = false;
    }
    
    Thread.sleep(this.interval);
   } catch (InterruptedException e) {
    Log.i("HIR", e.getMessage());
    e.printStackTrace();
   } catch (Exception e) {
    Log.i("HIR", "Error!");
   }

   this.handler.post(new Runnable() {
    public void run() {
     setValue(value, total);
    }
   });
  } }
 
 public void prepare(int stop, int interval) {
  this.stop = stop;
  this.value = this.start;
  this.total = this.stop;
  this.interval  = interval;
  if (this.thread.isAlive()) {
   this.thread = new Thread(this);
   this.done = false;
  }
  this.thread.start(); 
 }
 
 public void start() { this.count = true; }
 public void pause() { this.count = false; }
 public void stop() { this.count = false; this.done = false; setValue(0, 1); }
 public void setOnFinishListener(OnFinishListener f) { this.f = f; }
}

Step 5 : Go to activity_main.xml found in res->layout and copy the below code in it.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:meterview="http://schemas.android.com/apk/res/com.mia.circleprogress"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
 
    <LinearLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content" >
        <Button
         android:id="@+id/run"
         android:text="@string/run"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:layout_margin="5dp" />

    </LinearLayout>
    
    <com.mia.circleprogress.MeterView
     android:id="@+id/meter"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        meterview:spacing="10"
        meterview:lineWidth="5"
        meterview:lineColor="#0af"
        meterview:pathColor="#ccc" />
 
</LinearLayout>

Step 6 : Now open MainActivity.java from src->com.mia.circleprogress. Copy the below code into it.

MainActivity.java
package com.mia.circleprogress;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.progress_layout);
  
  final MeterView meter = (MeterView) this.findViewById(R.id.meter);
  meter.runAsync(false);
  meter.setOnFinishListener(new OnFinishListener() {
   public void onFinish() {
    Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
   }
  });
  
  final Button run = (Button) this.findViewById(R.id.run);  
  run.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
    
    run.setEnabled(false);
    
    new Thread(new Runnable() {
     public void run() {
      final int stop = 100;
      for (int i = 1; i <= stop; i++) {
       try {
        Thread.sleep(100);
       } catch (InterruptedException e) { }
       
       final int n = i;
       runOnUiThread(new Runnable() {
        public void run() {
         meter.setValue(n, stop);
        }
       });
      }
      runOnUiThread(new Runnable() {
       public void run() {
        run.setEnabled(true);
       }
      });      
     }
    }).start(); 
   }
  }); 
 }}

Step 7 : Run the application.

Explanation of the code:
Explanation from activity_main.xml :
  • First we define a LinearLayout under which we have another Linear Layout and a meterview widget which we made it ourselves.
  • In the inner LinearLayout we have a button with id=run. When we click the button the progress will start.
  • In the widget of meterview having id=meter we also have some attributes of type meterview which we have defined in attrs.xml file in res->values
Explanation from MeterView.java :
  • This class creates the widget MeterView which we have used in activity_main.xml.
  •  Explanation commented in the code above
Explanation from MainActivity,java :
  • The onFinish() method of the MeterView we will make a Toast displaying done.
  • In onClick() method of the Button run we will start a Thread which will run from 0 to 100.
Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 22.10.15

5 October 2015

Dialog Prompt before closing app

What we will do ?
-> We will use the default hello world application, if the back button is pressed then there will be a dialog box displayed whether to close the application.

What we will need ?
  • Dialog Box
  • Changes in MainActivity.java
Step 1 : Create a new Application. Click on File->New->Android Application Project.
file new android app

Step 2 : Give a name to your application (ExitPrompt) and package name as (com.mia.exitprompt). Click Next continuously.
Click Finish.

Step 3 : Open MainActivity.java from src->com.mia.exitprompt.

MainActivity.java
package com.mia.exitprompt;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
  
    public void onBackPressed(){  
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("Are you sure you want to exit ?")
  .setCancelable(false)
  .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    finish();
   }
  });

 .setNegativeButton("No", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface arg0, int arg1) {
   // TODO Auto-generated method stub 
  }
 });
  AlertDialog alert = builder.create();
  alert.show();
  }
}

Step 4 : Run the application. Press the Back button after the application is started.

Explanation of the code :
  • We have prepared an AlertBox. Using the setMessage() method we set the text to be displayed in the alert.
  • setCancelable(false) is used to tell the compiler that the alert box is not exited implicitly.
  • The positive button (yes) is used to exit the application by using finish() method.
  • The negative button (no) is used to be in the same activity by doing nothing inside it.
Github download
Stay Tuned with Made In Android

Published By:
swe moe
on 5.10.15

Next Page Home
Top