2017-04-03 196 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

我更喜欢你的答案,如果它有效,因为它不会改变我的代码。但是我发现自己的答案也发布了,这是行得通的。 –