简体   繁体   中英

How to use room database from Service or

Good day,

The app needs to monitor the incoming SMS even the app killed so I think Service is the best way to do the job but I faced the problem when I trying to call the viewmodel.

I am trying to select, insert, update, delete my room database from the background process using Service to my project. Here is my simple code.

public class ReadIncomingSMS extends Service {
    RoomViewModel model;

    @Override
    public IBinder onBind(Intent intent) { return null; }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        model = ViewModelProviders.of((FragmentActivity) getApplicationContext()).get(RoomViewModel.class);
    }
}

but the logcat says,

java.lang.RuntimeException: Unable to start service com.mgb.textvote.services.ReadIncomingSMS@3ae6b5cf with Intent { cmp=com.mgb.textvote/.services.ReadIncomingSMS }: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.fragment.app.FragmentActivity at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3119)

Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.fragment.app.FragmentActivity at com.mgb.textvote.services.ReadIncomingSMS.onStartCommand(ReadIncomingSMS.java:47)

if the application context cannot be cast to fragmentActivity then how can we use the room database inside the service or what is the best way to query in the background process?

You are trying to access FragmentActivity ViewModel in Service.

Create separate ViewModel for Service and it will work.

Thanks to Antonis answer,

instead of accessing FragmentActivity ViewModel in Service, I change the code like this.

To my MainActivity.java

public class MainActivity extends AppCompatActivity {
    public static RoomViewModel model;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        model = ViewModelProviders.of(this).get(RoomViewModel.class);
     }
}

then in my Service

instead of

model = ViewModelProviders.of((FragmentActivity) getApplicationContext()).get(RoomViewModel.class);

I changed it to

model = MainActivity.model;

I don't know if this method is a good practice but it seems works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM