- Widget
- Handler
- Service
Ex : 2015/05/12 17:00
需要在code裡不斷的重新更新時間,下面這段code就是new出一個新的時間並設定我們需要的格式。
new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" ).format( new Date())
在Widget的部分主要是要intent Service交由Service去處理我們的每秒更新與背景。
Widget.java
public class SmsWidget extends AppWidgetProvider {
Context context_main ;
AppWidgetManager app_manager;
int []appWidgetId;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
app_manager = appWidgetManager;
context_main = context;
appWidgetId = appWidgetIds;
//new出一個 intent並將Widget的context傳入
Intent intent = new Intent(context_main,WidgetService.class);
//Intent執行service服務
context_main.startService(intent);
}
@Override
public void onEnabled(Context context) {
}
@Override
public void onDisabled(Context context) {
//當WidgetDisable時關閉service服務
Intent intent = new Intent(context_main,WidgetService.class);
context_main.stopService(intent);
}
}
那我們要如何不斷的new出新的時間並更新widget的view ?
其實只要用handler來處理即可,並搭配Service讓code在背景執行,執行一次就更新一秒。
Service.java
public class WidgetService extends Service { private Handler mHandlerBoss = null; private HandlerThread mHandlerEmployee = null; private String EmployeeName = "John"; public WidgetService() { } @Override public void onDestroy() { super.onDestroy(); //service結束,結束handler mHandlerBoss.removeCallbacks(mRunnable); } @Override public int onStartCommand(Intent intent, int flags, int startId) { //建立Handler //Handler簡單來說就是需要老闆、員工、工作 //建立一個員工 mHandlerEmployee = new HandlerThread(EmployeeName); //員工上班 mHandlerEmployee.start(); //建立一個老闆,老闆聘員工上班 mHandlerBoss = new Handler(mHandlerEmployee.getLooper()); //老闆指派工作給員工 mHandlerBoss.post(mRunnable); return super.onStartCommand(intent, flags, startId); } private Runnable mRunnable = new Runnable() { @Override public void run() { //更新Widget畫面 buildUpdate(); //每秒跑一次 mHandlerBoss.postDelayed(this,1000); } }; private void buildUpdate() { RemoteViews view = new RemoteViews(getPackageName(), R.layout.sms_widget); view.setTextViewText(R.id.appwidget_text, new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" ).format( new Date())); ComponentName thisWidget = new ComponentName(this, SmsWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(thisWidget, view); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
編譯成功後就能夠在,手機裡將Widget拉出來使用。
參考連結:
Widget Update http://stackoverflow.com/questions/4866305/android-widget-update
背景執行 http://cooking-java.blogspot.tw/2010/04/android-service.html