2017-04-03 127 views
-3

我正在使用獨立於UI的Android服務創建通知。這工作非常好。以下是代碼。每30秒運行一次Android服務

​​

該服務也在系統啓動時自動啓動。 CheckNewEntry是我的AsyncTask,它檢查數據庫並在發生任何更改時發送通知。我還沒有添加CheckNewEntry,因爲它超出了這個問題的範圍。

現在我想要做的是,每30秒或1分鐘運行CheckNewEntry

任何人都可以幫忙嗎?

+0

使用處理程序方法 –

+0

您可以修改我的代碼,因爲我是Android開發新手?我一直在試圖這樣做,但失敗了。 –

+0

http://stackoverflow.com/a/13423036/3395198 –

回答

0

通過不同的問題#1 /回答去後,我設法拿出自己的解決方案。

下面是我創建並正在工作的代碼。

public class SendNotificationService extends Service { 
    public Context context = this; 
    public Handler handler = null; 
    public static Runnable runnable = null; 

    @Override 
    public void onCreate() { 
     handler = new Handler(); 
     runnable = new Runnable() { 
      public void run() { 
       String requested_method = "LoadBU"; 
       String bu_status = "1"; 

       CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this); 
       checkNewEntry.execute(requested_method, bu_status); 

       handler.postDelayed(runnable, 10000); 
      } 
     }; 

     handler.postDelayed(runnable, 15000); 
    } 

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

     return START_STICKY; 
    } 

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

    @Override 
    public void onDestroy() { 
     handler.removeCallbacks(runnable); 

     Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show(); 
    } 
} 

如果你們任何人都可以提供更好的解決方案,請張貼。

0

你可以使用像這樣的處理程序。

public class SendNotificationService extends Service { 
     Context context; 
     String test_heading; 
     String test_body; 
     public static Runnable runn; 
     public static Handler hand =new Handler(); 
     final class notifThread implements Runnable { 
      int service_id; 

      notifThread(int service_id) { 
       this.service_id = service_id; 
      } 

      @Override 
      public void run() { 
       String requested_method = "LoadBU"; 
       String bu_status = "1"; 

       CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this); 

    runn = new Runnable() { 
       @Override 
       public void run() { 

        checkNewEntry.execute(requested_method, bu_status); 

        hand.postDelayed(runn, 30000); 
       } 
      }; 


      runn.run(); 


      stopSelf(this.service_id); 
     } 
    } 

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

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Thread thread = new Thread(new notifThread(startId)); 
     thread.start(); 

     return START_STICKY; 
    } 

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

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

     Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show(); 
    } 
} 
+0

我現在要試一試。 –

+0

無法執行任務:任務已經執行(任務只能執行一次) –

+0

我更喜歡你的答案,如果它有效,因爲它不會改變我的代碼。但是我發現自己的答案也發佈了,這是行得通的。 –