Saturday, December 27, 2014

Home screen clock widget using canvas


Home screen clock widget using canvas

In my post Clock widget for home screen I explain you how to create clock widget now if you want to implementing to draw any thing using canvas in widget view then here is the example that draw the clock in widget view.


package com.widgetexam;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.IBinder;
import android.widget.RemoteViews;

public class WidgetService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
       
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handle.post(runnable);
        return super.onStartCommand(intent, flags, startId);
    }
   
    @Override
    public void onDestroy() {
        super.onDestroy();
        handle.removeCallbacks(runnable);
    }
    private SimpleDateFormat sdfTime = new SimpleDateFormat("HH:MM:ss");
    Handler handle = new Handler();
    Runnable runnable = new Runnable() {
       
        @Override
        public void run() {
            Bitmap bitmap = Bitmap.createBitmap(150, 75, Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            paint.setColor(Color.TRANSPARENT);
            canvas.drawPaint(paint);
            Paint textPaint = new Paint();
            textPaint.setColor(Color.CYAN);
            textPaint.setStyle(Style.FILL);
            textPaint.setTextSize(35);
            canvas.drawText(sdfTime.format(new Date()), 10, 50, textPaint);
            canvas.save();
           
            RemoteViews rviews = new RemoteViews(getPackageName(), R.layout.widget_layout);
            rviews.setImageViewBitmap(R.id.imageView, bitmap);
            ComponentName thiswidget = new ComponentName(
WidgetService.this,MyWidgetProvider.class);
            AppWidgetManager.getInstance(
WidgetService.this).updateAppWidget(thiswidget, rviews);
           
            handle.postDelayed(this, 1000);
        }
    };

}





Now next is Widget class which managing start/stop this service on update and delete time of the widget event.


public class MyWidgetProvider extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        context.startService(new Intent(context,WidgetService.class));
    }
   
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        context.stopService(new Intent(context,WidgetService.class));
    }
}


Happy to coding and happy to help you

Friday, October 31, 2014

Generate and Play a tone in Android

Generate and Play a tone in Android

Here is the code to generate and play the tone with frequency base in Android.

This will be playing for 3 second whenever you change the frequency rate by using seekbar it will be start play for 3 second.

PlaySound Activity


import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class PlaySound extends Activity{

    private final int duration = 3; // seconds
    private final int sampleRate = 8000;
    private final int numSamples = duration * sampleRate;
    private final double sample[] = new double[numSamples];
    private double freqOfTone = 500; // hz

    private final byte generatedSnd[] = new byte[2 * numSamples];

    Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        genTone();
        
        final TextView tv = (TextView)findViewById(R.id.textview);
        tv.setText(""+freqOfTone);
        SeekBar seekbar = (SeekBar)findViewById(R.id.seekbar);
        seekbar.setProgress((int)freqOfTone);
        seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    freqOfTone = seekBar.getProgress();
    tv.setText(""+freqOfTone);
    genTone();
    handler.post(new Runnable() {

                    public void run() {
                        playSound();
                    }
                });
   }
   
   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    
   }
   
   @Override
   public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    // TODO Auto-generated method stub
    
   }
  });
        
        
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Use a new tread as this can take a while
        final Thread thread = new Thread(new Runnable() {
            public void run() {
                
                handler.post(new Runnable() {

                    public void run() {
                        playSound();
                    }
                });
            }
        });
        thread.start();
    }

    void genTone(){
        // fill out the array
        for (int i = 0; i < numSamples; ++i) {
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
        }

        // convert to 16 bit pcm sound array
        // assumes the sample buffer is normalised.
        int idx = 0;
        for (final double dVal : sample) {
            // scale to maximum amplitude
            final short val = (short) ((dVal * 32767));
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSnd[idx++] = (byte) (val & 0x00ff);
            generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);

        }
    }

    AudioTrack audioTrack;
    void playSound(){
     if(audioTrack!=null){
      audioTrack.stop();
      audioTrack.release();
      audioTrack = null;
     }
     audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampleRate, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
                AudioTrack.MODE_STATIC);
        
        
        audioTrack.write(generatedSnd, 0, generatedSnd.length);
        audioTrack.play();
    }
}

Layout file which have TextView which display current frequency value and Seekbar to change the frequency.

<?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" >

    <SeekBar
        android:layout_margin="10dp"
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="3000" />

    
    <TextView
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Happy to help you, Happy to code

Wednesday, October 15, 2014

Clock widget for home screen


Create clock for home screen widget

Create new project without activity.

Create "xml" folder under "res" folder.

Create new xml file like widget_xml.xml under xml folder

Copy/paste below code in widget_xml.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_layout"
    android:minHeight="300dp"
    android:minWidth="175dp"
    android:updatePeriodMillis="1000" >

</appwidget-provider>

Now define receiver in you AndroidManifest.xml file, copy/past below code

<receiver android:name=".MyWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_xml" />
</receiver>

Create layout file for widget say widget_layout.xml in you res/layout this is for our widget layout which will be used to display current time.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dip" >

    <TextView
        android:background="#ffffff"
        android:textColor="#000000"
        android:id="@+id/update"
        style="@android:style/TextAppearance.Medium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="4dip"
        android:gravity="center_horizontal|center_vertical"
        android:padding="10dp"
        android:text="Static Text"
        android:textSize="20sp" >
    </TextView>

</LinearLayout>

Now create one class under your package having name MyWidgetProvider and copy/paste below code, extending the AppWidgetProvider which will create for widget we need to implementing onEnabled(), onDeleted(), onDisabled() method to managing our service for start and stop. While onUpdate() method will be used as for update the widget with new time on first time, this will be update on first time only.

public class MyWidgetProvider extends AppWidgetProvider {

 public void onEnabled(Context context) {
  super.onEnabled(context);
  context.startService(new Intent(context, UpdateWidgetService.class));
 }

 public void onDeleted(Context context, int[] appWidgetIds) {
  super.onDeleted(context, appWidgetIds);
  context.stopService(new Intent(context, UpdateWidgetService.class));
 }

 @Override
 public void onDisabled(Context context) {
  super.onDisabled(context);
  context.stopService(new Intent(context, UpdateWidgetService.class));
 }

 @Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {

  RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
    R.layout.widget_layout);
  remoteViews.setTextViewText(R.id.update,
    Utility.getCurrentTime("hh:mm:ss a"));
  ComponentName thiswidget = new ComponentName(context,
    MyWidgetProvider.class);
  AppWidgetManager manager = AppWidgetManager.getInstance(context);
  manager.updateAppWidget(thiswidget, remoteViews);
 }
}

Now create UpdateWidgetService which updating the widget value every 1 second. This service we need to create for updating the widget value. As onUpdate() will be called once so we need to update widget content value every second so for that we create this service and start new runnable with handle which will be calling recursively itself every 1 second to update the widget value.

public class UpdateWidgetService extends Service {
 private static final String LOG = UpdateWidgetService.class.getSimpleName();
 private Context context;
 
 private Handler handler = new Handler();
 private Runnable runn = new Runnable() {
  @Override
  public void run() {
   Log.i(LOG, "Called");
   //You can do the processing here update the widget/remote views.
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
       R.layout.widget_layout);
     remoteViews.setTextViewText(R.id.update, Utility.getCurrentTime("hh:mm:ss a"));
     ComponentName thiswidget = new ComponentName(context, MyWidgetProvider.class);
     AppWidgetManager manager = AppWidgetManager.getInstance(context);
     manager.updateAppWidget(thiswidget, remoteViews);
     handler.postDelayed(runn, 1000);
  }
 };
 @Override
 public void onDestroy() {
  super.onDestroy();
  if(handler!=null){
   handler.removeCallbacks(runn);
  }
  handler = null;
 }
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  context = this;
  handler.post(runn);
  return super.onStartCommand(intent, flags, startId);
 }

 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }
}

Now register this service class into your AndroidManifest.xml file

<service android:name=".UpdateWidgetService"/> 

Create java class for utility say Utility.java and copy/paste below code.

public class Utility {
 public static String getCurrentTime(String timeformat) {
  Format formatter = new SimpleDateFormat(timeformat);
  return formatter.format(Calendar.getInstance().getTime());
 }
} 

Now run this app, we don't have any activity so it will just install in your device. Long press on your home screen and select Widget option from them.

Search clock widget as it containing your application icon and hold and drag and drop on the home screen. It will be starting time as your current device time. On every 1 sec of delay from service it will be refresh the time.

Happy to coding and happy to help you

Saturday, October 4, 2014

Timer counter Logic



Timer counter logic

private TextView tvTimeCounter;
int hour, min, sec; // this all initiating with 0 by default;

Handler counterHandler = new Handler(); // Use handler for Runnable

// Counter Runnable which will called itself after 1 sec (Recursively)
Runnable counterRunnable = new Runnable(){
    @Override
        public void run() {
            if (sec == 59) {
                if (min == 59) {
                    hour++;
                    min = 0;
                } else {
                    min++;
                }
                sec = 0;
            } else {
                sec++;
            }

            updateTimer();
            counterHandler.postDelayed(this, 1000);
        }

}


// This method will be called every 1 sec and update your TextView with new time
public void updateTimer() {
        runOnUiThread(new Runnable() {
            public void run() {
                tvTimeCounter.setText(String.format("%02d:%02d:%02d", hour,
                        min, sec));

            }
        });
 


public void onCreate(Bundle bundle){
      super.onCreate(bundle);
      tvTimeCounter = new TextView();
      setContentView(tvTimeCounter);
}

public void onResume(){
     super.onResume();
     counterHandler.postDelay(counterRunnable); // on activity resume it will counter your counter
}

public void onPause(){
     super.onPause();
     counterHandler.removeCallback(counterRunnable); // on activity pause stop counter by removing handler
}



Just copy the above code and you have getting your Timer counter in Android

Happy to help you

Thursday, October 2, 2014

Customizing Progressbar in Android


Customizing Progressbar in Android

In default style you change the Progressbar from circular to horizontal. Now in that also you can change the color whatever you like it.

Here is the below code will change the color circular Progressbar. Its looks like this





circular_progress_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >
        <size
            android:height="76dip"
            android:width="76dip" />

        <gradient
            android:angle="0"
            android:endColor="#
00FF00"
            android:startColor="@android:color/transparent"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

Use this file in your Progressbar  like this way.

<ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/progress_drawable" />

Two main things you need to use i.e. android:indeterminate="true" to allow indeterminate and change the indeterminate drawable android:indeterminateDrawable="@drawable/progress_drawable" with our drawable.

Now for Horizontal progressbar






progress_horizontal_drawable.xml

<?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" />

            <gradient
                android:angle="270"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:startColor="#ff9d9e9d" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />

                <gradient
                    android:angle="270"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:startColor="#80ffd300" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />

                <gradient
                    android:angle="270"
                    android:endColor="#008000"
                    android:startColor="#33FF33" />
            </shape>
        </clip>
    </item>

</layer-list>

Use this file in Progressbar

<ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:id="@+id/progress"
            android:progress="50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:indeterminate="false"
            android:progressDrawable="@drawable/progress_drawable" />


Friday, September 19, 2014


First example in Android using L Preview API

Before start to create an example check this this post to create emulator using L Preview OS.

Step 1
Create new project and set the API level as show in below image


When you selecting L Preview API level for minimum required SDK same level will be set in Target SDK.

Looking for L Preview API for Compile with don't worry just select API 20 right now, we'll change it later on once Project is created.

Now just finish the rest of the thing with your requirement and finish wizard to start the project.

First we need to change the compile version as we use version kitkat 20 wear API level for this project instead of this need to apply L Preview. Right click on project and go the Android tab and select the L Preview level API and apply it.



Next thing need to apply Material Theme for your App, see below image as I removed other values folder from my project just keep the default values folder, open the style.xml file and remove current code and  write the new code as below

style.xml

<resources>
  <!-- inherit from the material theme -->
  <style name="AppTheme" parent="android:Theme.Material">
      <!-- Customize your theme here -->
  </style>
</resources>

This will be use the new theme for your Application.

Now change the code in your layout as for me I have created activity_main.xml in my project write the below new code.

<TextView
        android:layout_margin="5dp"
        android:id="@+id/my_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:elevation="5dp"
        android:text="@string/hello_world"
        android:textColor="#000000" />


android:elevation
The new translationZ property lets you create animations that reflect temporary changes in the elevation of a view. For example, this is useful to respond to touch gestures.

Start your emulator and run this project. This project only run under L Preview  OS.

Create Emulator using L Preview version in Android

You need to first download the latest API 20 level for this. Open your SDK Manager and download the SDK Platform API and any one system image file for your emulator as I below I have done check below image.



After download done open Android Virtual Device Manager

Look for Google Nexus 5 device definition in Device Definition Tab select it and click on create AVD button.

Now set this configuration for your Nexus 5 emulator as show in below image you can set whatever you want but few thing need required that is sdk must be L Preview level, check mark the option Use Host GPU, rest thing you can set as per your requirement.


Now click on OK it'll create new AVD for you then click on newly created AVD and start it. It'll take few minutes to create emulator as it's first time so it'll taking more time for start up. As its need to create skin and install the L Preview OS in this with its all pre-built App and service.

If you not check mark the Use Host GPU option it'll not able to create emulator as its need more process. Using this option this will use your system CPU in virtual device to create and start up.

Hope you successfully start up the Emulator with L Preview OS, if you have any query or doubt you can ask me.

My next post is create First example in L Preview

Tuesday, September 16, 2014


WhatsApp Messenger

New features available in Version 2.11.378

- More option provided in User chat conversation screen as below:
  • View Contact
             By tapping on person name on top heading view profile screen will be open but this option also provided in Option menu and open user's profile.
  • Call
            Now from the option menu you can directly call that person without going to user's profile or in Contact screen. With the warning message you can call that person just press the Call button.
  • Search
            Too much messages and hard to get that message, now you can search that message(s) too just select this option and it'll be high lighted that messages with yellow color which message contains search text.

- Profile option provided when you visiting any user's profile as below:
  • View in address book
            You can directly open current user's contact profile (If available in your contact) and view the more info from that profile too.
  • Pay for <Person Name>
            Now you can pay for your friend, beloved or anyone for extending WhatsApp App.

Tuesday, September 9, 2014


Store listing for Application in Android

Store listing is section of publishing your Android APK. If this section is not complete then you are not able to publish your APK. You can upload your APK on APK section but this not only things you need to provide details about this App so this section is for your Application details. Check the left section listing APK, Store listing, Pricing and Distribution etc. this are must green then only you are able to publish you App on Google Play Store.

How to know that store listing section is complete or not or something is missing to provide.

Left side option are indicating that which section are Green marked or not, if they are Green then you are ready to publish. Right side you see the Draft button that will be display as Ready to Publish button once all the requirement details you submit it and save it. If Draft button is still as it is then Why I not publish my App when you click on Draft button and click on that it'll list out the pending thing that you need to submit.

Here is the screen for Store listing screen shot I have provided for you.






Once you filled and provided all the requirement details then click on Save and if its all accepted then Draft button will change to Ready to Publish and you're able to publish you App now.

Monday, September 8, 2014

Create FirstExample applicaiton in Android

Create Android Application in Eclipse

Step 1: Select Android Project from the File->New option menu. If you not found then select option Project or Other. Now select Android->Android Application Project.



Step 2:  This is the first step of wizard, set the Project name whatever you like I set as FirstExam in the Application, same for Project name. Application name which is showing on the device and Project name is for Eclipse and try to avoid space an other thing in this.

Next set the package name for your Application com.example.firstexam this must be unique because Android OS managing all the Apps by package name.

Next select minimum version level of the App to support level.

Next select the target version level of the App.

Next select the compile version, here always select latest version to getting all the Android latest features and classes into your App. Also you will getting two different API for same level Android and Google API if you are going to use any Google API then only select Google API other just select Android.

Next thing if you required different theme want to apply then select it.

Now press next for the next step




Step 3: Here you can set the project location and project's other feature setting like create icon, activity etc. Just check the box whatever you want to create with project.

Note: If you want to create your project as library project then only checked the option library otherwise keep unchecked this option.

1. Create custom launcher icon
     In this you can create custom icon for your application by using existing image, clip art or Text with icon resize option and color modification as background and foreground

2. Create activity
     This will be as optional if you want create an single activity with project creation time then keep as it is, if you won't then unchecked. After creating custom icon this option also provided if you want to create activity

3. Mark this project as a library
    If you want to create library then check this option it will create jar file for you and you can integrate this project with other project and use this library in one or more project.
Note:  This will not be an executable project when you build.

4. Set the project location as default it will be the current workspace path would be set as project location you can check this option and change the location of your application.


Step 4: In this step if you check 1st option then only this will be the next screen otherwise it be skipped, you can navigate back and next any time.


Step 5: In next step provide feature to create activity with different pre-built and pre-coded activity by Android just select which type of activity you required and press next with checked create activity option. If you want create any activity then just unchecked the create activity option and click to finish.



Step 6: With the previous go with the create activity then only this will be available to set the name of your activity and layout file.


Now press finish as this is the last step or wizard. And after finish your application is ready to run in any of your supportive emulator or device with Hello World saying

After finish it will create project with single activity and its layout with Hello World message for you.

Now right click on the project select Run-> Android Application. This will run your application in your selected device.

You can do many thing while creating project time. Just explore more option with different way and you will be know more about this to create fast application with different stuff provided by Android.

Happy to help you.