Android 如何使用计时器?

Android 如何使用计时器?,android,android-intent,Android,Android Intent,我想改变背景,但我想用定时器来改变它。例如,早上我有一个背景,晚上我有另一个背景。但我不知道在安卓系统中使用什么。如果你有一个例子可以效仿。有什么想法吗?为了确保我理解你的意思,你想: -一段时间后更改背景或 -在不同的白天更改背景 为了完成第二个步骤,我将在OnCreate()方法中设置一个开关(或任何其他位置,例如OnResume(),单击按钮),以查找时间 Time t = new Time(); t.setToNow(); 然后决定使用哪个图像这是每天重复报警的代码。您必须从此活动

我想改变背景,但我想用定时器来改变它。例如,早上我有一个背景,晚上我有另一个背景。但我不知道在安卓系统中使用什么。如果你有一个例子可以效仿。有什么想法吗?

为了确保我理解你的意思,你想:

-一段时间后更改背景或
-在不同的白天更改背景

为了完成第二个步骤,我将在OnCreate()方法中设置一个开关(或任何其他位置,例如OnResume(),单击按钮),以查找时间

Time t = new Time();  
t.setToNow();

然后决定使用哪个图像

这是每天重复报警的代码。您必须从此活动中取出所需的代码(很抱歉)。您可以使用此代码设置每天早上9点重复的警报。您可以在您预期的时间为晚上添加相同的内容

public class AndroidScheduledActivity extends Activity {
    /** Called when the activity is first created. */
    int id = 115;
    Intent myIntent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button buttonStart = (Button)findViewById(R.id.start);

        myIntent = new Intent(getBaseContext(), MyScheduledReceiver.class);
        myIntent.putExtra("id", id);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(), id, myIntent, 0);

        alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

        buttonStart.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                setForMonday();
                finish();
            }});
    }

    public void setForMonday() {
        Calendar calendar = Calendar.getInstance();


        calendar.set(Calendar.DAY_OF_WEEK,2);
        calendar.set(Calendar.HOUR,09);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        System.out.println("Old is set@ :== " + calendar.getTime());


       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}
这是报警接收器

public class MyScheduledReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // here you can add the code to change the background

        System.out.println("Receiver");
    }

}

您还必须在清单文件中添加receiver。

使用alarmmanager,您可以向pending intent传递一个标志,以检测早晨或晚上,或者可以使用其他逻辑,如日期时间。假设OP只喜欢在应用程序启动时更改背景,那么我认为这是最优雅的解决方案。如果OP真的希望在应用程序运行时更改背景,这仍然是一个很好的解决方案,您只需要在其他地方运行测试,例如在按下按钮时,等等。