Android 如何安排每晚12点的任务

Android 如何安排每晚12点的任务,android,Android,我想在每天上午12点准时启动ScheduledExecutorService,但在我的代码中,没有启动ScheduledExecutorService。有人能告诉我我的代码是否正确吗?如果有其他可行的方法,也会很有帮助 public class MainActivity extends AppCompatActivity{ ScheduledExecutorService scheduler; @Override protected void onCreate(Bundle savedI

我想在每天上午12点准时启动ScheduledExecutorService,但在我的代码中,没有启动ScheduledExecutorService。有人能告诉我我的代码是否正确吗?如果有其他可行的方法,也会很有帮助

public class MainActivity extends AppCompatActivity{  
ScheduledExecutorService scheduler;

@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
scheduler = Executors.newScheduledThreadPool(1);

scheduleTask();

}

 public void scheduleTask() {

        final Runnable beeper = new Runnable() {
            public void run() {
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {


Toast.makeText(getApplicationContext(),"SCHEDULE STARTED",Toast.LENGTH_LONG).show();

                                    }
                                }
                            }
                        }, 1500);
                    }
                    });
            }
            };

        Calendar midnight = Calendar.getInstance();
        midnight.set(Calendar.HOUR_OF_DAY, 0);
        midnight.set(Calendar.MINUTE, 0);
        midnight.set(Calendar.SECOND, 0);
        midnight.set(Calendar.MILLISECOND, 1);
        midnight.set(Calendar.DAY_OF_YEAR, midnight.get(Calendar.DAY_OF_YEAR) + 1);
        long tillMidnight = midnight.getTimeInMillis() - System.currentTimeMillis() - 1;
        long ticksTillMidnight = tillMidnight / 50;

        final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, ticksTillMidnight,20*60*60*24, TimeUnit.MILLISECONDS
        );
        scheduler.schedule(new Runnable() {
            public void run() {
                beeperHandle.cancel(true);
            }
        }, 6*6,     TimeUnit.MILLISECONDS
        );
    }}
公共类MainActivity扩展了AppCompatActivity{
ScheduledExecutorService调度器;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduler=Executors.newScheduledThreadPool(1);
scheduleTask();
}
public void scheduleTask(){
最终可运行蜂鸣器=新可运行(){
公开募捐{
MainActivity.this.runOnUiThread(新的Runnable(){
公开募捐{
Toast.makeText(getApplicationContext(),“计划已开始”,Toast.LENGTH_LONG.show();
}
}
}
}, 1500);
}
});
}
};
日历午夜=Calendar.getInstance();
午夜。设置(日历。一天中的小时,0);
午夜。设置(日历。分钟,0);
午夜。设置(日历秒,0);
午夜设置(日历毫秒,1);
midnight.set(Calendar.DAY\u OF年,midnight.get(Calendar.DAY\u OF年)+1);
long-tillMidnight=midnight.getTimeInMillis()-System.currentTimeMillis()-1;
长时间滴答作响的午夜=直到午夜/50;
final ScheduledFuture beeperHandle=调度器。scheduleAtFixedRate(蜂鸣器,滴答声,午夜,20*60*60*24,时间单位:毫秒
);
scheduler.schedule(新的Runnable(){
公开募捐{
蜂鸣器手柄。取消(真);
}
},6*6,TimeUnit.ms
);
}}

答案很简单。在您的情况下,
ScheduledExecutorService
绑定到进程的生命周期。如果进程被终止,则
ScheduledExecutorService
将随之终止。而是使用
AlarmManager

这里有3个步骤

  • 创建警报
  • 创建广播接收器
  • 在应用程序清单中注册接收方
  • 1。创建报警

    public void createAlarm() {
        //System request code
        int DATA_FETCHER_RC = 123;
        //Create an alarm manager
        AlarmManager mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    
        //Create the time of day you would like it to go off. Use a calendar
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
    
        //Create an intent that points to the receiver. The system will notify the app about the current time, and send a broadcast to the app
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, DATA_FETCHER_RC,intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
        //initialize the alarm by using inexactrepeating. This allows the system to scheduler your alarm at the most efficient time around your 
        //set time, it is usually a few seconds off your requested time.
        // you can also use setExact however this is not recommended. Use this only if it must be done then.
    
        //Also set the interval using the AlarmManager constants
        mAlarmManager.setInexactRepeating(AlarmManager.RTC,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
    
    }
    
    2。创建广播接收器

    //This is the broadcast receiver you create where you place your logic once the alarm is run. Once the system realizes your alarm should be run, it will communicate to your app via the BroadcastReceiver. You must implement onReceive.
    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Your code once the alarm is set off goes here
            //You can use an intent filter to filter the specified intent
        }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package">
    //This is a useful permission as it allows your apps alarm to still be active once a reboot takes place
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
        <receiver
            android:name=".MainActivity$AlarmReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
    
    3。在应用程序清单中注册接收者

    //This is the broadcast receiver you create where you place your logic once the alarm is run. Once the system realizes your alarm should be run, it will communicate to your app via the BroadcastReceiver. You must implement onReceive.
    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Your code once the alarm is set off goes here
            //You can use an intent filter to filter the specified intent
        }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package">
    //This is a useful permission as it allows your apps alarm to still be active once a reboot takes place
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
        <receiver
            android:name=".MainActivity$AlarmReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
    
    
    //这是一个有用的权限,因为它允许您的应用程序在重新启动后仍处于活动状态
    

    ScheduledExecutorService与应用程序进程的生命周期绑定。这不是一种稳定的方式,因为应用程序随时可能被系统破坏。而是使用
    AlarmManager
    。检查下面的答案谢谢,如果你发现答案有帮助,请向上投票,以便其他人知道这可能对他们的情况有帮助hi@martinomburajr此代码对我有帮助,但每次打开应用程序时,也会启动计划,因此如何消除此代码。请给我任何解决办法。谢谢。你能详细说明一下你想要什么吗?这样我就可以帮你了。我不太清楚你所说的“计划开始了,那么如何消除这个计划”是什么意思