我的代码在单击按钮时运行得非常好,但我现在需要自动在Alarm Service中运行它。当我调用方法(updateDays()
)在**Runnable**
接口中执行时,它根本不会被调用。数据库未按预期更新。我真的做得对吗?
DbAdapter mDbHelper;
Cursor mCursor;
Runnable mUpdateTask = new Runnable() {
public void run() {
long maxWaitTime = System.currentTimeMillis() + 10*1000;
while (System.currentTimeMillis() < maxWaitTime) {
synchronized (mBinder) {
try {
updateDays();
mBinder.wait(maxWaitTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
private void updateDays() {
mDbHelper.open();
if(mCursor != null) {
mDbHelper.updateDL (DbAdapter.KEY_ID,
mCursor.getInt(mCursor.getColumnIndex(DbAdapter.KEY_DAYS))-1,
DbAdapter.KEY_DATE_TIME);
mDbHelper.close();
Toast.makeText(this, "Update done !", Toast.LENGTH_SHORT).show();
}
}
修改
广播接收器中的 onReceive
方法
public void onReceive(Context context, Intent intent) {
int rowid = intent.getExtras().getInt(DbAdapter.KEY_ID);
Intent i = new Intent(context, AlarmService.class);
i.putExtra(DbAdapter.KEY_ID, rowid);
context.startService(i);
}
编辑2
我的服务**onCreate**
方法
@Override
public void onCreate() {
mNofitication = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotification();
Thread tr = new Thread(null, mUpdateTask, "AlarmService");
tr.start();
}
答案 0 :(得分:1)
如果您的服务覆盖NullPointerException
并且不链接到超类,那么我可以看到您可以在IntentService.java
的第116行获得onCreate()
的唯一方法。
答案 1 :(得分:0)
根据您的要求,我觉得您需要使用待处理的意图以及警报管理器。相同的样本如下所示:
//Creating a PendingIntent
Intent intent = new Intent(MainActivity.this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(
MainActivity.this, UNIQUE_ID_RANDOM, intent, 0);
//Creating an AlarmManager and setting the pendingIntent to him
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (5 * 1000), pendingIntent);
Toast.makeText(MainActivity.this, "Alarm set in " + 5 + " seconds",
Toast.LENGTH_SHORT).show();
现在在服务开始后你说5秒,你可以把你的上面的代码,并试一试。以下是样本:
public class MyService extends Service{
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Your database opening code should come here. But take care of the syntax related constructs.
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
我希望这会对你有所帮助。
此致
ZAX