android implements widget clock example sharing

  • 2020-05-30 21:00:56
  • OfStack

1. Configure Widgets in AndroidManifest.xml:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.widget"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".TimeWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/timewidget_info" />
        </receiver>
        <service android:name=".TimerService"></service>
    </application>
</manifest>

2. Create the xml directory under the res directory of the project, and create the timewidget_info.xml file as follows:


<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/time_appwidget"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:updatePeriodMillis="0" />

3. Create a file time_appwidget.xml in the layout folder:


<?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" 
    android:background="@drawable/rectangle"
    >
    <TextView 
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:text="current time"
        />
</LinearLayout>

4. Create the rectangle.xml file in the drawable folder (this can be omitted, mainly to beautify the TextView control, the gradient effect) :


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <!--  Set the radian  -->
    <corners android:radius="9dp" />
    <gradient
        android:angle="270"
        android:endColor="#5EADF4"
        android:startColor="#B3F0FF" />
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
    <stroke
        android:dashGap="1dp"
        android:dashWidth="10dp"
        android:width="6dp"
        android:color="#0000FF" />
</shape>

5. Background code implementation:


package com.example.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
public class TimeWidgetProvider extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }
    // when 1 a Widgets Will be called 
    public void onDeleted(Context context, int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onDeleted(context, appWidgetIds);
    }
    // The first 1 Next to the desktop Widgets Will be called, and then the same type will be added Widgets Will not be called 
    public void onEnabled(Context context) {
        context.startService(new Intent(context, TimerService.class));
    }
    // Delete the last from the desktop 1 a Widgets Will be called 
    public void onDisabled(Context context) {
        context.stopService(new Intent(context, TimerService.class));
    }
}


package com.example.widget;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
public class TimerService extends Service {
    private Timer timer;

    @Override
    public void onCreate() {    
        super.onCreate();
        timer = new Timer();
        timer.schedule(new MyTimerTask(), 0, 1000);
    }
    private final class MyTimerTask extends TimerTask{
        @SuppressLint("SimpleDateFormat")
        @Override
        public void run() {
            SimpleDateFormat sdf= new SimpleDateFormat("hh:mm:ss");
            String time = sdf.format(new Date());
            // To obtain Widgets manager 
              AppWidgetManager widgetManager =AppWidgetManager.getInstance(getApplicationContext());
            //widgetManager The operation of the Widget The corresponding remote view is the current Widget the layout file 
              RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.time_appwidget);
            remoteView.setTextViewText(R.id.textView, time);
            // When you click Widgets When triggered by the world 
            //remoteView.setOnClickPendingIntent(viewId, pendingIntent)
            ComponentName componentName = new  ComponentName(getApplicationContext(),TimeWidgetProvider.class);
            widgetManager.updateAppWidget(componentName, remoteView);
        }
    }
    @Override
    public void onDestroy() {
        timer.cancel();
        timer=null;
        super.onDestroy();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}


Related articles: