我无法找到如何public bool SaveDataCapDetails(List<TDataCapDetails> lstDataCapDetails)
{
bool IsSuccess = false;
using (var dbContextTransaction = _objContext.Database.BeginTransaction())
{
try
{
int? id = _objContext.TDataCapDetails.Max(x => (int?)x.Id);
id = id == null ? 0 : id;
// entities with Id == 0 --> new entities
// you may need to check if Id == null as well (depends on your data model)
var entitiesToAdd = lstDataCapDetails.Where(x => x.Id == 0);
foreach(var entity in entitiesToAdd)
{
entity.Id = id++;
// new entities is not tracked, its state can be changed to Added
_objContext.Entry(entity).State = EntityState.Added;
}
// entities with Id > 0 is already exists in db and needs to be updated
var entitiesToUpdate = lstDataCapDetails.Where(x => x.Id > 0);
foreach (var entity in entitiesToUpdate)
{
// check if entity is being tracked
var local = _objContext.Set<TDataCapDetails>().Local.FirstOrDefault(x => x.Id.Equals(entity.Id));
// if entity is tracked detach it from context
if (local != null)
_objContext.Entry<TDataCapDetails>(local).State = EntityState.Detached;
// attach modified entity and change its state to modified
_objContext.Attach(entity).State = EntityState.Modified;
}
// optional: assign value for IsSuccess
IsSuccess = _objContext.SaveChanges() > 0;
dbContextTransaction.Commit();
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
throw ex;
}
}
return IsSuccess;
}
在服务中。
例如接收者:
public class BroadcastReceiverOnBootComplete extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) { Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(serviceIntent); } else { context.startService(serviceIntent); } } } }
在getAssets
类中,如何获取AndroidServiceStartOnBoot
?
非常感谢。
已编辑:
问题不是如何在getContext().getAssets().open("server.crt");
类中调用getAssets
,而是问题是如何在服务BroadcastReceiverOnBootComplete
类中getAssets
。
我发布AndroidServiceStartOnBoot
类的原因是因为这就是我所说的BroadcastReceiverOnBootComplete
类。抱歉,这有点误导。谢谢。
答案 0 :(得分:2)
onReceive为您提供广播接收器类中的上下文
public abstract void onReceive (Context context, Intent intent)
从那里开始,您可以直接使用它或将其分配给您的类级变量,也可以在其他方法中使用它
Context myContext = null;
@Override
public void onReceive(Context context, Intent intent) {
//here you can access to context directly
context.getAssets().open("MY_FILE");
//or you can save it in your class level variable
myContext = context;
// now you can use this myContext to other methods of this class
}
的固有内容修改
因此在服务中,您可以直接这样做...
Context context = this;
答案 1 :(得分:0)