【问题标题】:Android How to execute a method every x hours or minutes [duplicate]Android如何每x小时或分钟执行一次方法[重复]
【发布时间】:2014-08-08 15:59:56
【问题描述】:

我正在尝试使用警报服务运行一个名为 Updater() 的方法,为了进行测试,我希望它每 1 分钟更新一次,最终每 2 小时更新一次。如果切换按钮打开,则计划任务在计时器上自行执行,并在切换按钮关闭时停止计时器 到目前为止,这是我的代码。有人可以告诉我我做错了什么吗?

 public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        Updater();
    }
}
public void autoUpdateClick(View view)
{
    AlarmManager alarmManager=(AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this,AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    boolean on = ((ToggleButton) view).isChecked();
    if (on)
    {
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),30000,pendingIntent);
        Toast.makeText(getBaseContext(),"Check-In will be done every 2 hours",Toast.LENGTH_SHORT).show();
    }
    else
    {
     alarmManager.cancel(pendingIntent);
        Toast.makeText(getBaseContext(),"Manual Check-In enabled",Toast.LENGTH_SHORT).show();
    }

}

【问题讨论】:

  • 你的问题到底是什么??
  • 该方法不是每 2 分钟执行一次 @Lal
  • 可能想看看HERE 似乎这已经被问及回答了。
  • 谢谢! @SimplyCraig5

标签: java android


【解决方案1】:

正如您所提到的,我们将安排警报在未来的特定时间执行方法。

我们将有两个班级

  1. MainAcitvity:在这个类中,我们将安排报警为 在特定时间触发。
  2. AlarmReciever:报警时 在预定时间触发,该类将收到警报,并且 执行一个方法。

AlarmReciever 类扩展了 BroadcastReceiver 并覆盖了 onRecieve() 方法。在 onReceive() 中,您可以根据需要启动一个活动或服务,例如您可以启动一个活动来振动手机或让手机响铃

需要权限 我们需要在应用程序中使用 AlarmManger 的权限,所以不要忘记在清单文件中声明权限

AndroidManifest 文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.src"
    android:versionCode="1"
    android:versionName="1.0" >

        <uses-sdk android:minSdkVersion="8"
                         android:targetSdkVersion="17" />
         <!-- permission required to use Alarm Manager -->
        <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>


        <application
                 android:icon="@drawable/ic_launcher"
                 android:label="Demo App" >
                <activity
                           android:name=".MainActivity"
                           android:label="Demo App" >
                          <intent-filter>
                                       <action android:name="android.intent.action.MAIN" />
                                       <category android:name="android.intent.category.LAUNCHER" />
                          </intent-filter>
               </activity>


            <!-- Register the Alarm Receiver -->
                   <receiver android:name=".AlarmReciever"/> 
            
         </application>
</manifest>

main.xml

<LinearLayout
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"
    android:gravity="center_vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">


<TextView
    android:id="@+id/textView1"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Alarm Manager Example"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/button1"
    android:layout_marginTop="25dp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Schedule The Alarm" 
    android:onClick="scheduleAlarm"/>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity
{
       @Override
       public void onCreate(Bundle savedInstanceState) 
      {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
      }

    public void scheduleAlarm(View V)
    {
            // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time, 
            // we fetch  the current time in milliseconds and added 1 day time
            // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day        
            Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

            // create an Intent and set the class which will execute when Alarm triggers, here we have
            // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
            // alarm triggers and 
            //we call the method inside onRecieve() method of Alarmreciever class
            Intent intentAlarm = new Intent(this, AlarmReciever.class);
       
            // create the object
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            //set the alarm for particular time
            alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
            Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
         
    }
}

AlarmReciever.java

public class AlarmReciever extends BroadcastReceiver

{
         @Override
            public void onReceive(Context context, Intent intent)
            {
               //call the method here
                         
             }
      
}

【讨论】:

  • 所以我需要将我的 Updater() 代码放在一个单独的类 alarmreciever.java 中并从那里调用它?
  • 有没有办法在不唤醒手机并使其嗡嗡作响的情况下做到这一点?
猜你喜欢
  • 2014-01-10
  • 2019-09-27
  • 2019-11-10
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2016-11-07
相关资源
最近更新 更多