Start service every X second with the help of thread as database update frequently

后端 未结 1 719
一生所求
一生所求 2021-01-21 12:11

My app is connected with SQL SERVER database which updates daily, so when i start my activity, log-in form pop-up and user logged in . Now as m

相关标签:
1条回答
  • 2021-01-21 12:23

    You can use IntentService along with a Timer as below:

    public class MyBackgroundService extends IntentService
    {
    private Timer mBackGroundTimer;
    public MyBackgroundService()
        {
            super("myservice");
            this.mBackGroundTimer=new Timer();
        }
    @Override
    protected void onHandleIntent(Intent intent) 
        {
            // TODO Auto-generated method stub
            mBackGroundTimer.schedule(new TimerTask() 
                { 
                    public void run() 
                        { 
    
                            try 
                                {
                                    //your db query here
                                } 
                            catch (Exception e) 
                                {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                        } 
                },startTime,repeatTime); 
        } // END onHandleIntent()
    private void mStopTimer()
        {
            //Call this whenever you need to stop the service
            mBackGroundTimer.cancel();
        }
    }
    

    and call this inside your activity as below:

    Intent mInt_BckGrndSrv =  new  Intent(getApplicationContext(),MyBackgroundService.class);
            startService(mInt_BckGrndSrv);
    

    and don't forget to specify it as a service in your manifest.xml as,

    <service android:name="com.example.MyBackgroundService" android:enabled="true"></service>
    

    P.S. For tutorial on different services, check this.

    0 讨论(0)
提交回复
热议问题