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
No comments:
Post a Comment