繁体   English   中英

每隔x秒发送一次通知

[英]Send notification every x seconds

我正在做一个检查实时分数的应用程序。 我不知道这是不是最好的方法,但我创建了一个Timertask,一个服务和Activity来通知。

如果分数发生变化,Timertask会每x秒检查一次,如果更改,则通知服务。 如果通知服务,它将调用将通知用户的活动。 我的问题是我没有把活动叫做服务通知。

这是我的代码(例如,我没有拿分数而是变量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);
    }
}

如果需要资源,系统可以终止服务。 根据您的要求,最好使用AlarmManager定期执行某些操作。

以下是更多参考文献: [1][2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM