我正在做一个检查实时比分的应用程序。我不知道这是否是最好的方法,但我创建了一个 Timertask、一个 Service 和一个 Activity 来通知。
Timertask 每 x 秒检查一次分数是否发生变化,如果发生变化,通知服务。如果 Service 被通知,它会调用将通知用户的 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);
}
}