android - Use IntentService with AndroidViewModel
问题描述
I need to perform some background calculation task in a project using MVVM
design pattern.
I have tried AsyncTask
and IntentService
in my ViewModel
but with no success. The calculation process is working well, but I have problems in getting the result from it. The result is a simple boolean to notify that the process is done.
Attached below the IntentService
version. I understand that I doing something wrong, but not sure what it is. Please help!
This is what I done so far:
IntentService;
public class mIntentService extends IntentService {
private static final String TAG = "mIntentSer";
public static final String URL = "urlpath";
String urlPath = "";
private MutableLiveData<Boolean> isTaskCompleted = new MutableLiveData<>();
//Array of images supported extensions
static final String[] EXTENSIONS = new String[]{
"jpeg", "jpg"
};
public mIntentService() {
super("mIntentService");
}
public MutableLiveData<Boolean> getResult(){
return isTaskCompleted;
}
//Filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
@Override
protected void onHandleIntent(Intent intent) {
urlPath = intent.getStringExtra(URL);
//some logic here
//then:
isTaskCompleted.postValue(true);
}
public static Bitmap rotateImage(Bitmap source, float angle) {
//some logic here
}
private void saveFile(Bitmap imageToSave, String fileName) {
//some logic here
}
}
MainActivityViewModel:
public class MainActivityViewModel extends AndroidViewModel {
mIntentService mIntentService;
public MainActivityViewModel(@NonNull Application application) {
super(application);
mIntentService = new mIntentService();
}
public LiveData<Boolean> getTheResult() {
Intent intent = new Intent(getApplication().getApplicationContext(), mIntentService.class);
intent.putExtra(mIntentService.URL, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/album/");
getApplication().startService(intent);
return mIntentService.getResult();
}
}
Observer in MainActivity:
mainActivityViewModel.getTheResult().observe(MainActivity.this, new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean blogList) {
Toast.makeText(getApplicationContext(), "DONE " + blogList, Toast.LENGTH_LONG).show();
}
});
Thank you!
解决方案
推荐阅读
- c++ - 读取逗号分隔的 .txt 文件并放入数组
- wpf - WPF 中 DataTemplate 或 HierarchicalDataTemplate 的 DataType 属性的格式是什么?
- node.js - 如何从 http.get 获取数据
- c# - C# 修改 file.txt 时,将副本保存到存档文件夹
- javascript - 如何在动态加载的按钮中发送新消息?
- python - BeautifulSoup 在某些下载请求中提取 div 对象,但在其他请求中不提取
- go - http.get("https://poe.ninja/data") 返回 "https://poe.ninja" 而不是域的所需路径
- c - 在c中的编译时确定数组中的位置
- arrays - 在 MATLAB 中从非常大的数据集生成直方图的有效方法?
- javascript - 创建多个 onmouseover 事件时,它们会继续“覆盖”前一个事件,直到代码仅识别最后一个事件