保持后台服务用户退出应用程序后,活着 [英] keeping background service alive after user exit app

查看:250
本文介绍了保持后台服务用户退出应用程序后,活着的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造一些服务甚至在用户,会做后台工作,我从关闭正在运行的进程菜单中的应用程序(通过换挡过程在屏幕)。

我试图做的是通过声明它像这样建立在不同的进程服务:

 <服务
        机器人:service.ServiceNAME =
        机器人:启用=真
        机器人:图标=@绘制/ ic_launcher
        机器人:工艺=:my_process>
  < /服务>

和onStartCommand()是:

  @覆盖
公众诠释onStartCommand(意向意图,诠释标志诠释startId){
    返回START_STICKY;
}


解决方案

这样做的一种方式。假设你有一个名为DoSomething的服务类。在 Android清单声明:

 <服务机器人:名字=.DoSomething>< /服务>

在服务类:

 处理程序处理程序=新的处理程序();可运行可运行=新的Runnable(){    @覆盖
    公共无效的run(){
        // TODO自动生成方法存根
        YourMethod();
        handler.postDelayed(这一点,1000); // 1000 - 毫秒
    }
 };

和最后:

  @覆盖
公众诠释onStartCommand(意向意图,诠释标志诠释startId){
    // TODO自动生成方法存根
     handler.postDelayed(可运行,1000);     返回START_STICKY;
}

从你的活动:

 意向意图=新意图(这一点,DoSomething.class);
startService(意向);

我希望它能帮助。

I'm trying to create some service that will do background jobs for me even after the user closes the app from the running processes menu(by shifting process up the screen).

What I tried to do is create service in a different process by declaring it like this:

  <service
        android:name=".service.Service"
        android:enabled="true"
        android:icon="@drawable/ic_launcher"
        android:process=":my_process" >
  </service>

and the onStartCommand() is:

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

解决方案

One Way of Doing This. Suppose you have a Service Class named "DoSomething". In Android Manifest Declare:

<service android:name = ".DoSomething"></service>

In the Service Class:

Handler handler = new Handler();

Runnable runnable = new Runnable(){

    @Override
    public void run() {
        // TODO Auto-generated method stub
        YourMethod();
        handler.postDelayed(this, 1000); // 1000 - Milliseconds
    }
 };

And Finally:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub


     handler.postDelayed(runnable, 1000);

     return START_STICKY;
}

From your Activity:

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

I hope it helps.

这篇关于保持后台服务用户退出应用程序后,活着的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆