我正在开发Android应用程序。我需要运行服务以每隔几秒检查一次数据库更新,并在更改时通知用户。
使用服务是解决这个问题的好方法吗?
这是我的代码的一部分。到目前为止,我还没有让它发挥作用。
任何帮助?
public class NotificationService extends Service {
private Timer mTimer;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
public String formattedDate, restoredText;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(timerTask,2000,15*1000);
Log.d("TEST","TEST");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
}catch (Exception e){
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Log.e("Log", "Running");
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
restoredText = prefs.getString("username", null);
if (restoredText != null) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formattedDate = df.format(c.getTime());
//notifiy(); //ovdje cemo ga privremeno iskljuciti
/*
here I need implement code for checking data from remotly mysql database
*/
}else {
notifiy();
}
}
};