gpt4 book ai didi

java - 杀死应用程序后继续运行计时器

转载 作者:行者123 更新时间:2023-11-30 01:31:47 26 4
gpt4 key购买 nike

我的应用程序中有以下计时器:

public class MainScreen extends ApplicationActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);

Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}

public static class ScheduleSomething extends TimerTask {
@Override
public void run() {
System.out.println("This is a test!");
}
}
}

每一秒都有消息“这是一个测试!”显示,但当我关闭应用程序时,它也会停止计时器。当我关闭应用程序时,有什么方法可以让这个计时器保持运行吗?

我尝试过:

public void onStop(Bundle savedInstanceState) {
super.onStop(savedInstanceState);

Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}

public void onDestroy(Bundle savedInstanceState) {
super.onDestroy(savedInstanceState);

Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleSomething(), 1000, 1000);
}

但是没用...

最佳答案

每分钟杀死应用程序后,使用广播接收器继续运行计时器:

public class TimerReceiverSyncInterval extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
scheduleAlarms(context);
context.startService(new Intent(context, NotificationServiceSyncInterval.class));
Log.d("TAG", "Sync OnReceive");
}

public static void scheduleAlarms(Context paramContext) {
Calendar calendar = Calendar.getInstance();
AlarmManager localAlarmManager = (AlarmManager) paramContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent localPendingIntent = PendingIntent.getService(paramContext, 0,
new Intent(paramContext, NotificationServiceSyncInterval.class), PendingIntent.FLAG_UPDATE_CURRENT);

localAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
(1 * 60000), localPendingIntent);
}
}

在下面的类中,在每分钟从 TimerReceiverSyncInterval 类调用的 onHandleIntent 方法中做任何你想做的事情:

public class NotificationServiceSyncInterval extends IntentService {

public NotificationServiceSyncInterval() {
super("Tracker");
}

public NotificationServiceSyncInterval(String paramString) {
super(paramString);
}

@Override
protected void onHandleIntent(Intent intent) {
//ToDo: put what you want to do here
Log.d("TAG", "Handler call");
}
}

在 list 文件中输入:

<receiver
android:name="com.yourpackage.TimerReceiverSyncInterval"
android:enabled="true" >
<intent-filter android:priority="999" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>

<service android:name="com.yourpackage.NotificationServiceSyncInterval" />

最后像这样从 MainActivity 注册广播接收器:

TimerReceiverSyncInterval.scheduleAlarms(this);

关于java - 杀死应用程序后继续运行计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35653908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com