作者residentevil (.....)
看板AndroidDev
标题[问题] 请问App Widget更新的问题
时间Tue Sep 13 19:54:21 2011
目前在研究app widget, 书上讲到如果更新太频繁
必须要自己用thread之类的方式来更新,
我在看下列程范例式码的时候碰到一些疑问
不知道为什麽需要在 thread中又去startservice来做更新
如果我把service中的updateAppWidget拿到onupdate或是thread部分都会出错
请问能大概解释一下为什麽程式需要这样写,
又为什麽updateAppWidget只能写在service中咧?
感谢!
public void onUpdate(final Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds)
{
Toast.makeText(context, "onUpdate", Toast.LENGTH_LONG).show();
startTimer(context);
}
// 下面这段是更新用的 thread
public static void startTimer(final Context context){
// Set Handler
final Handler handler = new Handler();
final Runnable callback = new Runnable() {
public void run() {
Intent intent = new Intent(context, MyService.class);
context.startService(intent);
}
};
// Create a thread to run
thread = new Thread() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
Log.i("thread", "thread: "+new Date().toLocaleString());
handler.post(callback);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
//MyService服务程式
public static class MyService extends Service {
@Override
public void onStart(Intent intent, int startId) {
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.what_time_is_it_now);
remoteViews.setTextViewText(R.id.TextView01, new
Date().toLocaleString());
ComponentName thisWidget = new ComponentName(this, WhatTimeIsItNow.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, remoteViews);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.128.110.82