Service

Reference: http://blog.csdn.net/pi9nc/article/details/18764415

 

Service needs to execute onCreate(), onStartCommand() and onDestroy() methods, and Service runs in the main thread.

Construct the Intent object, call the startService() method and stopService() method to start and stop the Service

Note: Every Service in the project must be registered in AndroidManifest.xml,

<Service  android:name-"">  </Service>

 

When a Service is started, the onCreate() and onStartCommand() methods in the Service are called.

The onCreate() method will only be called when the Service is created for the first time. If the current Service has already been created, no matter how the startService() method is called, the onCreate() method will not be executed again, only onStartCommand() will be executed. method

 

Communication between Service and Activity:

 

1. There is an onBind() method in Service, which is used to associate with Activity

2. First create an anonymous class of ServiceConnection in the Activity, which rewrites the onServiceConnected() method and the onServiceDisconnected() method. These two methods will be called when the Activity and the Service are associated and disassociated respectively.

3. In the onServiceConnected() method, assign the service to the instance object of MyBinder

4. In the click event, construct an Intent object, and then call the bindService() method to bind the Activity and the Service.

The bindService() method receives three parameters. The first parameter is the Intent object just constructed. The second parameter is the instance of the ServiceConnection created earlier. The third parameter is a flag bit. After being associated with the Service, the Service is automatically created, which will make the onCreate() method in MyService execute, but the onStartCommand() method will not execute.

5. If you want to release the association between the activity and the Service, just call the unbindService() method.

Note: Any Service is common to the entire application, that is, MyService can not only associate with MainActivity, but also associate with any Activity, and they can all obtain the same MyBinder instance when the association is established.

Example:

Service file:

public class MyService extends Service {

    public static final String TAG="MyService";
    private MyBinder mBinder=new MyBinder();

    @Override
    public void onCreate() {
        Log.e(TAG,"onCreate() executed");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"onStartCommand() executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG,"onDestroy() executed");
        super.onDestroy ();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class MyBinder extends Binder{
        public void startDownload(){
            Log.e(TAG,"Start downloading...");
        }
    }
}

 Activity file:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button button;
    private MyService.MyBinder myBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder= (MyService.MyBinder) service;
            myBinder.startDownload ();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,MyService.class);
                bindService(intent,connection,BIND_AUTO_CREATE);
            }
        });
        Log.e(TAG, "start onCreate~~~");
    }
}

 

Destruction of Service:

 

1. Execute the startService() method first, then execute the stopService() method, and the Service is destroyed

2. Execute the bindService() method first, then execute the unbindService() method, the Service is destroyed

3. The startService() method is executed, and the bindService() method is executed. Both stopService() and unbindService() methods must be executed to destroy the Service, and neither of them can destroy the Service.

 

Note: We must remember to clean up those resources that are no longer used in the onDestroy() method of the Service, to prevent some objects that are no longer used still occupying memory after the Service is destroyed.

 

 The relationship between Service and Thread:

 A child thread needs to be created in the Service, because all Activities can be associated with the Service, and then the methods in it can be easily manipulated. Even if the Activity is destroyed, as long as it is re-associated with the Service, it can obtain the original An instance of Binder in the Service.

Standard Service:

 

@Override  
public int onStartCommand(Intent intent, int flags, int startId) {  
    new Thread(new Runnable() {  
        @Override  
        public void run() {  
            // start executing background tasks  
        }  
    }).start();  
    return super.onStartCommand(intent, flags, startId);  
}  
 
class MyBinder extends Binder {  
  
    public void startDownload() {  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                // Execute the specific download task  
            }  
        }).start();  
    }    
}  
Create a foreground Service: Create a Notification object in the onCreate() method of the Service, then call the setLatestEventInfo() method to initialize the layout and data for the notification, and open the MainActivity after setting the click notification here. Then call the startForeground() method to turn the Service into a foreground Service and display the notification picture. E.g:
    @Override
    public void onCreate() {
        Log.e(TAG,"onCreate() executed");
        Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());
        super.onCreate();

        Intent builderIntent=new Intent(this,MainActivity.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,builderIntent,0);
        Notification.Builder builder=new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)                 
                    .setContentTitle("This is the title of the notification")
                    .setContentText("This is the content of the notification")
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(pendingIntent);
        Notification notification=builder.getNotification();
       startForeground(1,notification);
    }
  Remote Service:      

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326824612&siteId=291194637