首页 > 解决方案 > 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!

标签: androidviewmodelandroid-viewmodelandroid-intentserviceandroid-mvvm

解决方案


推荐阅读