I haven’t written a blog for a long time. Today I write a basic thing, that is how to write a Service that runs in the background for a long time.

First we need to write a Service as follows:

public class MyService extends Service{ private int one; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); new Thread(new Runnable() { @Override public void run() { while (true){ try { Log.i("infomationHaha",one+""); one++; Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); }}Copy the code

This onCreate is what’s going to run for a long time. The onCreate method is executed only once on the first execution, and onStartCommand is executed once each time a Service is started.

Configuration of the manifest file

<service android:name=".MyService"></service>
Copy the code

Start the Service

Intent intent = new Intent(this,MyService.class);
startService(intent);
Copy the code

After the corresponding Service is configured, we can start the Service and execute the code.