1. 程式人生 > >Android widget簡介及demo

Android widget簡介及demo

文章目錄

1、簡介

實現桌面小部件
在這裡插入圖片描述

2、檔案結構

在這裡插入圖片描述

1)appwidget_info.xml 定義了 widget 一些屬性
2)AndroidManifest.xml 定義 widget 屬性 宣告
3)main_activuty.xml 想要顯示 的widget xml
4)MyWidget.java 繼承 AppWidgetProvider 實現對widget 的操作監聽
5)WidgetService.java 實現對widet 資料的操作
6)MainActivity.java 沒執行什麼

3、res->xml->appwidget_info.xml

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/main_activity"
    android:minHeight="80dp"
    android:minWidth="250dp"
    android:previewImage="@mipmap/ic_launcher"
    android:updatePeriodMillis="0"
    android:widgetCategory="home_screen|keyguard">

</appwidget-provider>
<!--

initialLayout :  widget 的佈局檔案
 minHeight: widget  的 最低高度
 minWidth : widget  的最低高度
 previewImage : widget 的預覽圖
 android:updatePeriodMillis : 更新的頻率  google 規定最小時間30 min
                              在這裡設定 0 我們自定義
 widgetCategory : widget 可以被新增主螢幕或者鎖屏
-->

4、main_activity.xml

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingLeft="30dp"
        android:paddingRight="30dp">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="日期:"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/tv_money"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#000"
                android:text="毫秒值:"
                android:textSize="16sp" />

        </LinearLayout>

        <Button
            android:id="@+id/btn_refound"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="點選"
            android:textColor="#000"
            android:textSize="16sp" />

    </LinearLayout>

</LinearLayout>

5、AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tssh.mywidget">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyWidget">

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

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

        </receiver>

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

    </application>

</manifest>

6、MyWidget.java

package com.example.tssh.mywidget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyWidget extends AppWidgetProvider {
    String TAG = "MyWidget:" ;
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.i(TAG ,"接受廣播");
    }

    /**
     * 第一個widget被新增呼叫
     * @param context
     */
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        Log.i(TAG ,"widget  onEnabled 狀態");
        context.startService(new Intent(context, WidgetService.class));

    }

    /**
     * widget被新增 || 更新時呼叫
     * @param context
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Log.i(TAG ,"widget  onUpdate 狀態");
        context.startService(new Intent(context, WidgetService.class));
    }

    /**
     * 最後一個widget被刪除時呼叫
     * @param context
     */
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        Log.i(TAG ,"widget  onDisabled 狀態");
        context.stopService(new Intent(context, WidgetService.class));
    }

    /**
     * widget被刪除時呼叫
     * @param context
     * @param appWidgetIds
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        Log.i(TAG ,"widget  onDeleted 狀態");

    }
}

7、WidgetService.java

package com.example.tssh.mywidget;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;

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

public class WidgetService  extends Service {

    String  TAG = "WidgetService ";
    private Timer mTimer;
    private SimpleDateFormat mFormat;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG,"更新 widget");
                updateWidget(WidgetService.this);  //更新 widget
            }
        }, 0, 5000);

    }

    private void updateWidget(Context context) {

        //通過 RemoteViews 載入佈局檔案
        //通過 setTextView 等方法實現對控制元件的控制
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main_activity);
        long millis = System.currentTimeMillis();
        String format = mFormat.format(new Date(millis));
        Log.i(TAG,"millis :" + millis + "\n"
                         + "format: " + format);
        remoteViews.setTextViewText(R.id.tv_date, "日  期:" + format);
        remoteViews.setTextViewText(R.id.tv_money, "毫秒值:" + millis);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btn_refound, pendingIntent);   //點選跳轉

        ComponentName componentName = new ComponentName(this, MyWidget.class);
        AppWidgetManager.getInstance(this).updateAppWidget(componentName, remoteViews);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        mTimer.cancel();
        mTimer = null;
Log.i(TAG,"onDestory");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

}

8、MainActivity.java

package com.example.tssh.mywidget;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    String TAG  = "MainActivity ";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        Log.i(TAG,"主介面");
    }
}

文獻參考:
Android例子—Widget的簡單使用介紹
https://blog.csdn.net/u012758088/article/details/53908054

android之Widget開發詳解例項一
https://blog.csdn.net/jason0539/article/details/10034377

Android開發之建立App Widget和更新Widget內容
https://www.cnblogs.com/liyiran/p/5268117.html

Android Widget小元件開發(一)——Android實現時鐘Widget元件的步驟開發,這些知識也是不可缺少的!
http://www.cnblogs.com/jzssuanfa/p/7105073.html