Reputation: 810
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 my database update any second , i want to run a query every X second so that any change in database is notified and send notification to user. So , I think thread will come in play so that query run every second . Now, i want to know how to implement Thread in this and run Service for notification so that whenever data is updated in database user will be notified via push notification.
Upvotes: 2
Views: 1488
Reputation:
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.
Upvotes: 3