开发者

Android start service from activity/asynctask

开发者 https://www.devze.com 2023-04-11 13:21 出处:网络
I see a lot of questions about starting an activity from a service, but I am not sure how to start the service from the activity.

I see a lot of questions about starting an activity from a service, but I am not sure how to start the service from the activity.

I want this to happen in an asynctask

Where the user loads an activity, some blocking background processing is done, and a service is started.

This service does i开发者_如何学JAVAts own logic in the deeper background and can be modified by changes to variables in the visual activities

How would this be done? I've read some tutorials but still dont find it intuitive


Simply use startService() with an intent that refers to your service. There is nothing special. If you need to pass parameters, you can set them in the Intent's extras. Cf. http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)


This is nothing to start the service just use the following code.

Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);

As per your question and my understanding

Simple start service from Activity or you can start in the same manner from async task. As per your flow i am giving just sample code

MainActivity.java

MyAsyncTask myTask = new MyAsyncTask(this);
myTask.execute();

Now goto method of ASYNC Task doInBackground() , you can start the service by using intent.

Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);

Now you want to update your MainActivity.java then you can use interface or you can startActivity(intent) by putting value like putExtra() method as per your requirement. but i will suggest kindly use interface to update your activity from service .

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号