首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >后台进程/服务

后台进程/服务
EN

Stack Overflow用户
提问于 2014-05-25 00:50:12
回答 1查看 108关注 0票数 0

我正在为我的高中最终安卓项目做一个简单的宏安卓应用程序,我想让一个后台进程,每隔一定的时间运行(由用户决定),以更新当前位置和其他一些事情作为条件来启动他们选择的行动,降低亮度或更改智能手机到静音模式或其他一些action....how,以使该进程(或服务),请记住,我是完全初学者(我甚至不知道进程或服务之间的区别)。所以,如果可以的话,请用示例代码来回答。谢谢!:D

EN

回答 1

Stack Overflow用户

发布于 2014-05-25 04:48:53

要执行定期更新/监控/其他操作,您需要从应用程序启动一个服务。这里有一个简短的解释:

http://www.basic4ppc.com/android/forum/threads/creating-a-sticky-service-long-running-background-tasks.27065/

下面是详细的长篇文章:

http://developer.android.com/guide/components/services.html

您可能需要前台服务,但sticky也可以工作,这取决于特定的要求。以下是一些基本代码(与第一个链接中描述的方式略有不同,但大体相同):

在AndroidManifest.xml中声明您的服务:

代码语言:javascript
复制
    <service android:name="Foo"/>

扩展Service类

代码语言:javascript
复制
    public class FooService extends Service {

    ..........

        @Override
    public void onCreate() {

         //if you want this service to run in the foreground so it doesn't get 
             //killed by the system, create a notification, and call this
             startForeground(id, notification); //look at the Service API

             //start your periodic monitoring thread
             ................

        }

        @Override
    public void onDestroy() {

          //do the cleanup here
          ................

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

          //whatever you need to do when the app calls the start command, 
          //which may happen multiple times, goes here
          ...............

           //this makes sure the process is sticky (see links above for details
           return START_STICKY; 
    }


        ..........


    }

在主活动的onCreate方法中,执行以下操作:

代码语言:javascript
复制
    Context context = getApplicationContext();
    Intent i= new Intent(context, FooService.class);
    i.putExtra(whetever you want to pass to the service)
    context.startService(i); 
    context.bindService(i, connection, 0); //read the API
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23847474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档