我创建了一个小部件来显示每 5-10 秒刷新一次的当前日期(稍后将增加持续时间)。在 onUpdate 方法中创建了一个警报以创建服务的意图。创建了一个扩展广播接收器的 onReceive 方法)以启动服务,该服务又使用日期更新小部件。当我调用小部件时,onReceive 最初会触发并显示日期。之后,警报不会响起。
1) 我是否正确包含 onReceive 方法并调用 startservice?2)我怎么知道创建警报是活动的并且没有触发?3)以下代码有什么问题?
请帮忙。
谢谢,山姆
public class WorldCupScores extends AppWidgetProvider {
public static String TAG = "myActivity";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "receiveeeeeeeeeeee");
Toast.makeText(context, "Receiver", Toast.LENGTH_LONG).show();
context.startService(new Intent(context, UpdateService.class));
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// To prevent any ANR timeouts, we perform the update in a service
//context.startService(new Intent(context, UpdateService.class));
AlarmManager alarmManager;
Log.d(TAG, "before intenttttt");
Intent intent = new Intent(context, UpdateService.class);
Log.d(TAG, "afterrrr intenttttt");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, 0);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5*1000, pendingIntent);
Toast.makeText(context, "My alarm started", Toast.LENGTH_LONG).show();
Log.d(TAG, "alarmmmmmmmm");
}
public static class UpdateService extends Service {
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "Inside Serviceeeeeeeeeeeeeeeeeeeee");
// Build the widget update for today
//RemoteViews updateViews = buildUpdate(this);
RemoteViews updateViews = new RemoteViews(this.getPackageName(),
R.layout.main);
Date date = new Date();
updateViews.setTextViewText(R.id.scores, "Current Time "
+ date);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(this, WorldCupScores.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
// We don't need to bind to this service
return null;
}
}
}