我创建了一个小部件来显示每5-10秒刷新的当前日期(稍后会增加持续时间)。 在onUpdate方法中创建一个警报,以创建服务的意图。 创建了一个扩展广播接收器的onReceive方法来启动服务,然后使用日期更新小部件。 当我调用onReceive小部件时最初触发并显示日期。之后警报不会触发。
1)我是否正确包含onReceive方法并调用startservice? 2)我如何知道创建警报是否激活而不是触发? 3)以下代码有什么问题?
请帮忙。
谢谢,Sam
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;
}
}
}
答案 0 :(得分:0)
1)我是否正确包含onReceive方法并调用startservice?
我不会这样做。在您当前的代码中,永远不会调用onUpdate()
,因为onReceive()
永远不会链接到超类。
2)我如何知道创建警报是否处于活动状态且未触发?
如果没有开火,则不活动。并且,由于未调用onUpdate()
,因此您的警报永远不会被安排。