gpt4 book ai didi

java - Android 每 5 秒循环一次服务并在启动时启动

转载 作者:行者123 更新时间:2023-12-02 07:54:22 25 4
gpt4 key购买 nike

我有下面的代码,我想每 5 秒循环一次。我尝试使用广播接收器和警报管理器,但没有成功。我希望我的服务循环 5 次,然后永久停止。这是我发布的第二个问题。请有人帮我修复代码,我在我的 mac 上堆了 2 天。任何帮助将不胜感激。

每 5 秒循环一次的代码

File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
try {
key.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

InfoReceiver.class 服务

public class InfoReceiver extends Service {

@Override
public void onCreate()
{
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 5);
alarmMgr.set(AlarmManager.RTC_WAKEUP, 5000, pendingIntent);
}
}

InfoManager.class 服务

public  class InfoManager extends Service {
@Override
public void onCreate() {
File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
try {
key.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

MyBroadcastreceiver.class

public class MyBroadcastReceiver extends BroadcastReceiver {
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, InfoManager.class);
context.startService(startServiceIntent);
}
}

list 代码

<service
android:name=".InfoReceiver"
android:enabled="true" >
</service>
<service
android:name=".InfoManager"
android:enabled="true" >
<intent-filter>
<action android:name=".InfoManager" />
</intent-filter>
</service>
<receiver
android:name=".MyBroadcastReceiver"
android:process=":remote" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

最佳答案

使用Handler.postDelayed(Runnable r,长delayMillis)。您不需要计时器或警报管理器来执行您想要的操作。保持简单。

关于java - Android 每 5 秒循环一次服务并在启动时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840784/

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