簡體   English   中英

具有后台任務的Android服務

[英]Android service with background task

我正在嘗試創建具有后台任務的服務。 線程啟動並執行該過程后的24小時。

我已經嘗試過了 但它沒有用。

public class MyService extends Service {

int counter = 0;
static final int UPDATE_INTERVAL = 10 * 1000; // / 1000 = 1 second
private Timer timer = new Timer();
Home home;

private boolean isRunning = true;

@Override
public IBinder onBind(Intent intent) {
    // Not implemented...this sample is only for starting and stopping
    // services.
    // Service binding will be covered in another tutorial
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    // Announcement about starting
    Toast.makeText(this, "Starting the Demo Service", Toast.LENGTH_SHORT)
            .show();

    // Start a Background thread
    isRunning = true;
    // Thread backgroundThread = new Thread(new BackgroundThread());
    BackgroundThread();

    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    // Stop the Background thread
    isRunning = false;

    // Announcement about stopping
    Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT)
            .show();
}

private void BackgroundThread() {

    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Calendar c = Calendar.getInstance();
            String month = String.valueOf(c.get(Calendar.MONTH) + 1);
            String year = String.valueOf(c.get(Calendar.YEAR));
            String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
            String months = null;
            if (month.startsWith("0") || month.startsWith("1")) {
                months = year + "-" + month + "-" + day;
                home.loadCalender(months);
            } else {
                months = year + "-" + "0" + month + "-" + day;
                home.loadCalender(months);
            }

        }
    }, 0, UPDATE_INTERVAL);
    /*
     * counter = 0; while(isRunning) { System.out.println(""+counter++);
     * //Thread.currentThread().sleep(5000);
     * 
     * }
     */

    System.out.println("Background Thread is finished.........");
}

}

在我的主要活動中,我已經啟動了Service ... plz幫助我執行此任務。

使用AlarmManager使用setRepeating() (或setInexactRepeating()將您的警報安排為每天發生一次,請不要浪費用戶的RAM試圖一直在監視時鍾滴答地運行服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM