gpt4 book ai didi

java - 每 x 秒发送一次通知

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

我正在制作一个检查实时比分的应用程序。我不知道这是否是最好的方法,但我创建了一个 Timertask、一个 Service 和一个 Activity 来通知。

Timertask 每 x 秒检查一次分数是否发生变化,如果发生变化,则通知服务。如果服务收到通知,它将调用通知用户的 Activity 。我的问题是我无法从服务调用通知 Activity 。

这是我的代码(例如,我没有获取分数,而是获取了变量 i。

   //import ...

public class MyService extends Service{

Notif notif = new Notif();

private static final String TAG = "MyService";

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}

@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
Timer time = new Timer(); // Instantiate Timer Object
final ScheduleTask st = new ScheduleTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 5000); // Create Repetitively task for every 1 secs
}

@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}

public void checkI(int i){
if (i==3){
notif.initializeUIElements();
}
}
}

定时器任务

import ...

// Create a class extends with TimerTask
public class ScheduleTask extends TimerTask {
MyService myService = new MyService();
Notif notif = new Notif();
int i = 0;
// Add your task here
public void run() {
i++;
System.out.println("affichage numero " + i );
myService.checkI(i);
}

public int getI() {
return i;
}
}

通知

import ...

public class Notif extends Activity {

private static final int NOTIFY_ME_ID = 1987;
private NotificationManager mgr = null;
ScheduleTask scheduleTask = new ScheduleTask();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

void initializeUIElements() {
Notification note = new Notification(R.drawable.ic_launcher,
"Welcome to MyDoople.com", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);

note.setLatestEventInfo(this, "MyDoople.com", "An Android Portal for Development",
i);
// note.number = ++count;
note.flags |= Notification.FLAG_ONGOING_EVENT;

mgr.notify(NOTIFY_ME_ID, note);
}
}

最佳答案

如果需要资源,系统可能会终止服务。根据您的要求,最好使用AlarmManager定期做某事。

这里有更多引用:[1] , [2]

关于java - 每 x 秒发送一次通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603315/

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