我有两个类,一个是MainActivity扩展了activity,另外一个是AlarmReceiver扩展了BroadcastReceiver。我怎么能够消除AlarmReceiver,而是在MainActivity实现这个功能?我知道不可能同时扩展两个类,所以我想知道最好的方法应该是什么?
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleNextUpdate();
Streamer str = new Streamer();
Calendar calendar = str.getIcs();
int x = 1;
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component component = (Component) i.next();
TextView tv_1 = new TextView(this);
layout.addView(tv_1);
tv_1.setText("Component " + x);
x++;;
for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
Property property = (Property) j.next();
TextView tv_2 = new TextView(this);
layout.addView(tv_2);
tv_2.setText(property.getName() + ": " + property.getValue());
}
}
}
public void scheduleNextUpdate()
{
Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = (currentTimeMillis *2) + DateUtils.MINUTE_IN_MILLIS;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);
if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 22)
{
nextUpdateTime.hour = 8;
nextUpdateTime.minute = 0;
nextUpdateTime.second = 0;
nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000,60000,pendingIntent);
Streamer str = new Streamer();
boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
new Intent(MainActivity.this,AlarmReceiver.class),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
}
System.out.println(currentTimeMillis);
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("myTag", "Alarm has been received");
intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
Streamer str = new Streamer();
Calendar calendar = str.getIcs();
System.out.println(calendar);
}
}