运行 持续后台服务

Run a service in background continuously

运行 持续在后台运行的服务。例如,必须启动一个服务,即使应用已关闭,它也会显示一次吐司消息 20 秒。

public class AppService extends IntentService {

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

    public AppService() {
        super("AppService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
        SystemClock.sleep(20000);
    }
}

在您声明服务的清单中,添加:

android:process=":processname"

这让服务 运行 在一个单独的进程中,因此它不会被应用程序杀死。

然后您可以选择是否要使用前景。它将显示持久通知,但会降低服务被终止的可能性。

此外,如果您想创建连续 运行ning 服务,请使用 ServiceNOT IntentService。 IntentService 在完成其操作时停止。

下面的代码适合我...

public class AppService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}
}

这段代码对我有用..

public class ServiceClass extends Service {

    public static final int notify = 300000;  //interval between two services(Here Service run every 5 Minute)
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Log.d("service is ","Destroyed");
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("service is ","running");
                }
            });
        }
    }
}

已接受的答案不适用于 Android 8.0(API 级别 26),请参阅 android 的背景限制 here

接受答案修改:

1: 您必须在启动服务后的 5 秒内调用服务的 startForeground() 方法。为此,您可以在 onCreate() 服务方法中调用 startForeground()

public class AppService extends Service {
    ....
    
    @Override
    public void onCreate() {
        startForeground(9999, Notification())
    }

    ....
} 

2: 您必须通过检查要启动服务的 API 级别来调用 startForegroundService() 而不是 startService()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}