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

No comments:

Post a Comment