The Android Service uses an example. The background task detects and restarts the application regularly.
Service Description:
Service is an application component that can perform long-running operations in the background without user interface. The service can be started by other application components (such as Activity). Once the service is started, it will always run in the background. Even if the component (Activity) that starts the service has been destroyed, it will not be affected. In addition, components can bind to services to interact with them, or even perform interprocess communication (IPC). For example, services can handle network transactions, play music, perform file I/O, or interact with content providers, all in the background.
In some cases, it is necessary to implement background scheduled tasks, detect and restart applications, which is very appropriate to use service.
usage method:
RestartAppService Service class inherits from Service:
/** * Restart app service * @author yangyongzhen * */ public class RestartAppService extends Service { private static final String TAG = "RestartAppService"; private static final long RESTART_DELAY = 60*60 * 1000; // How long does it take to restart the test (1 hour) private MyBinder mBinder; // This object is used for communication between the bound service and the caller public class MyBinder extends Binder { /** * Get service instance * @return */ public RestartAppService getService() { return RestartAppService.this; } /** * Start app restart task */ public void startRestartTask(final Context context) { Toast.makeText(context, "restart check", Toast.LENGTH_SHORT).show(); Log.e(TAG,"restart app check"); TimerTask task = new TimerTask() { @Override public void run() { //When the timing time is up, check whether it is after 12 p.m. String curtime = DateUtils.getDatedf18(); if(DateUtils.isInTime(curtime,"23:59","00:59")){ //During processing period Log.e(TAG,curtime); Log.e(TAG,"in time area 23:59--00:59,begin restart"); // restart Intent intent = getPackageManager().getLaunchIntentForPackage( getApplication().getPackageName()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); System.exit(0); } } }; Timer timer = new Timer(); timer.schedule(task, RESTART_DELAY); } } @Override public IBinder onBind(Intent intent) { // Create MyBinder object Log.e(TAG,"onBind"); if (mBinder == null) { mBinder = new MyBinder(); } return mBinder; } @Override public boolean onUnbind(Intent intent) { Log.e(TAG, "onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.e(TAG,"onDestroy"); super.onDestroy(); } }
Next, you need to open the Android manifest XML.
<service android:name=".service.RestartAppService" android:enabled="true" android:exported="true"/>
android:exported indicates whether programs other than the current program are allowed to access the service android:enabled indicates whether the service is enabled android:permission is a permission statement Whether android:process needs to run in a separate process. When it is set to android:process = ": remote", it represents that Service runs in a separate process.
Note: it means to append the current package name before the current process name, so "remote" and ": remote" do not have the same meaning. The process name of the former is: remote, and the process name of the latter is: app packagename: remote. android:isolatedProcess setting true means that the service will run under a special process, which is separate from other processes in the system and does not have its own permissions. The only way to communicate with it is through the API of the service (bind and start).
Complete Service binding and start Service in Application or Activity:
...... /** * ServiceConnection Represents the connection to the service. It has only two methods, * onServiceConnected And onservice disconnected, * The former is called when the operator successfully connects to a service, while the latter is called when the connection is interrupted due to service crash or killing */ private RestartAppService myService; private ServiceConnection connService = new ServiceConnection() { /** * Called when a connection to the Service has been established, * with the android.os.IBinder of the communication channel to the Service. */ /** * The interface method interacting with the server is called back when binding the Service. This method obtains the IBinder object passed by the binding Service, * Through this IBinder object, the interaction between host and Service is realized. */ @Override public void onServiceConnected(ComponentName name, IBinder service) { RestartAppService.MyBinder mBinder = (RestartAppService.MyBinder) service; myService = mBinder.getService(); mBinder.startRestartTask(App.this); } @Override public void onServiceDisconnected(ComponentName name) { myService = null; } }; @Override public void onCreate() { super.onCreate(); sInstance = this; mContext = getApplicationContext(); Log.i(TAG, "==app onCreate=="); // Record exception log //Create a binding object and bind a service to periodically restart the app Intent intent = new Intent(this, RestartAppService.class); bindService(intent, connService, Context.BIND_AUTO_CREATE); }
Created a ServiceConnection object that represents the connection to the service.
It has only two methods, onServiceConnected and onServiceConnected, which have the following meanings:
- onServiceConnected(ComponentName name, IBinder service) The system calls this method to pass the IBinder returned by the onBind() method of the service. Service is the IBinder implementation class object returned by the server. Through this object, we can call to obtain the LocalService instance object, and then call the public method of the server. ComponentName is a class that encapsulates the information of components (Activity, Service, BroadcastReceiver, or ContentProvider), such as package name, component description and other information. This parameter is rarely used.
- onServiceDisconnected(ComponentName name) The Android system will call this method when the connection to the service is unexpectedly interrupted (for example, when the service crashes or is terminated). Note: the system will not call this method when the client unbinds.
Service lifecycle analysis:
When binding the service bindService, the onCreate() and onBind methods of the RestartAppService server will be called in turn.
At this point, the serviceconnection Onserviceconnected() is called and returns the MyBinder object.
mBinder. The getservice method returns the instance object myService of RestartAppService. At this time, the client holds the instance object of RestartAppService, and can arbitrarily call the declared public method in the RestartAppService class.
myService is not used here because it is only a simple timing detection restart.
What happens if you try to call the bindService method multiple times to bind the RestartAppService server?
The onBind method of RestartAppService is called only once, that is, the onBind method will be called back when bindService is called for the first time.
If you call unbindService(connService) to unbind, the onUnBind and onDestroy methods of RestartAppService will be called back in turn, and you only need to unbind once for multiple bindings.
Description: the Service life cycle method calls in the binding state are onCreate(), onBind, onUnBind, and onDestroy.