android从窗口小部件调用定时器运行函数
问题描述:
我在每个10分钟运行的窗口小部件中都有一个定时器,但是当我按下按钮时,我需要调用定时器运行函数。有什么办法呢?android从窗口小部件调用定时器运行函数
public class MyWidget extends AppWidgetProvider {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
//call the run function of the timer
}
super.onReceive(context, intent);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if(tt==0) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1000, 600000);
tt=1;
}
}
private class MyTime extends TimerTask {
public MyTime(Context context, AppWidgetManager appWidgetManager) {
}
@Override
public void run() {
}
我需要CAL从的onReceive()这个函数
答
你可以在进myWidget类中创建一个方法,并从两者中指明MyTime对应的run方法和的onReceive这样称呼它:
public class MyWidget extends AppWidgetProvider {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
//call the run function of the timer
doStuff();
}
super.onReceive(context, intent);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if(tt==0) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1000, 600000);
tt=1;
}
}
private class MyTime extends TimerTask {
public MyTime(Context context, AppWidgetManager appWidgetManager) {
}
@Override
public void run() {
doStuff();
}
}
private void doStuff() {
// Stuff that needs to be done in run and onReceive
}
}
答
你指的是什么运行方法?
有类定时器()
没有运行方法。如果你试图执行类指明MyTime对应的run方法,通过一个线程启动以来的TimerTask实现Runnable -
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
//call the run function of the timer
MyTime myTime = new MyTime();
Thread thread = new Thread(myTime);
thread.start();
}
“我有一个定时器在我的小部件中每10分钟运行一次“ - 不,你不知道。 Android可以并将在应用程序小部件更新之间终止您的过程。当Android终止你的进程时,你的'Timer'和'TimerTask'就会消失。因此,你的'TimerTask'永远不会被调用。如果您希望每10分钟更新一个应用程序小部件,请使用'AlarmManager'。 – CommonsWare 2012-02-08 17:46:16