我正在做一个检查实时分数的应用。我不知道这是不是最好的方式,但我创建了一个Timertask,一个服务和活动来通知。
如果分数发生变化,则每隔x秒检查一次Timertask,如果更改,则通知服务。 如果通知服务,它将调用将通知用户的活动。我的问题是我没有把活动叫做服务通知。
这是我的代码(例如,我没有拿分数而是变量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();
}
}
}
的TimerTask
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;
}
}
NOTIF
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);
}
}