亲爱的:使用定期服务。我有同样的问题,我像这样解决了。就我而言,这是代码。
服务代码:
public class PeriodicService extends Service {
private static final long TIMEREQ = 10000 * 60;// 10 mints
public static String LOG = "Log";
private final Context mContext;
public UpdateServices(Context context) {
this.mContext = context;
}
public UpdateServices() {
super();
mContext = UpdateServices.this;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i(LOG, "Service started");
// save in sqlite after 10 mints
DatabaseManger db = new DatabaseManger(mContext);
db.open();
db.insert("anything", "data");
db.close();
// upload data to somewhere server
new CreateNewProduct(this).execute();
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Intent ishintent = new Intent(this, UpdateServices.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
TIMEREQ, pintent);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Intent ishintent = new Intent(this, UpdateServices.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pintent);
Toast.makeText(this, "service stoped", Toast.LENGTH_SHORT).show();
}
}
你可以得到帮助from here
启动和停止您的服务
调用启动服务。根据服务的生命周期,在服务停止时调用destroy方法。根据您的选择,在服务延迟一段时间的情况下,停止服务后不使用挂起意图。
来自 Activity 调用
btn_startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(About.this, UpdateServices.class));
}
});
btn_stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(About.this, UpdateServices.class));
}
});
用于列表视图刷新您的列表适配器。