Services of four Android Components

Source: Internet
Author: User

 

In many cases, some applications that seldom need to interact with users can be run in the background, and we can still run other applications while they are running.

To process this background process, Android introduces the concept of Service. Service is a long-lived component in Android, which does not implement any user interface.

Basic Concepts

Movie Service is a component that runs in the background and has no interface. It is called by other components.

 

Secret creates a Service, defines class inheritance Service, and defines in AndroidManifest. xml <service>

 

Ÿ enable Service and call the startService method in other components

 

The stopService method is called.

 

1. Call service in activity

 

 

/*

* Enable the Service

*/

Public void start (View view ){

Intent intent = new Intent (this, MyService. class );

StartService (intent );

}

/*

* End Service

*/

Public void stop (View view ){

Intent intent = new Intent (this, MyService. class );

StopService (intent );

}

2. Define Service:

 

 

Public class MyService extends Service {

 

/*

* Called during binding

*/

Public IBinder onBind (Intent intent ){

Return null;

}

 

/*

* Called when the service is enabled

*/

Public void onCreate (){

Super. onCreate ();

System. out. println ("onCreate ");

}

 

/*

* Called when the service is terminated

*/

Public void onDestroy (){

Super. onDestroy ();

System. out. println ("onDestroy ");

}

}

 

3. Define the service in the configuration file: <service android: name = ". PMyService"/>

 

Telephone recording

 

The telephone recording is implemented by the Service. It runs in the background and listens to the phone status using the listener. When the phone is called, The Listener obtains the phone number of the incoming phone. After the user receives the call, the recording starts. When the phone call is suspended, the recording is stopped and saved to sdcard.

 

Java code:

 

 

@ Override

Public void onCreate (){

// Get the telephone service

TelephonyManager manager = (TelephonyManager) getSystemService (Context. TELEPHONY_SERVICE );

// Call status listener

Manager. listen (new MyListener (), PhoneStateListener. LISTEN_CALL_STATE );

}

 

Private final class MyListener extends PhoneStateListener {

Private String num;

Private MediaRecorder recorder; // recording

Private File file;

Public void onCallStateChanged (int state, String incomingNumber ){

Switch (state ){

// Bell status

Case TelephonyManager. CALL_STATE_RINGING:

// Save the phone number

Num = incomingNumber;

Break;

// Connection status

Case TelephonyManager. CALL_STATE_OFFHOOK:

Try {

// Set the file storage location

File = new File (Environment. getExternalStorageDirectory (), num + "_" + System. currentTimeMillis () + ". 3gp ");

// Create a recorder

Recorder = new MediaRecorder ();

// Set the audio source (MICROPHONE)

Recorder. setAudioSource (AudioSource. MIC );

// Save in 3gp format

Recorder. setOutputFormat (OutputFormat. THREE_GPP );

// Sets the encoder.

Recorder. setAudioEncoder (AudioEncoder. AMR_NB );

// Output file path

Recorder. setOutputFile (file. getAbsolutePath ());

// Prepare

Recorder. prepare ();

// Recording

Recorder. start ();

} Catch (Exception e ){

E. printStackTrace ();

}

Break;

// Call idle status

Case TelephonyManager. CALL_STATE_IDLE:

// Stop recording AFTER THE PHONE HANGS UP

If (recorder! = Null ){

Recorder. stop ();

Recorder. release ();

}

Break;

}

}

}

 

Permission:

 

 

<! -- Read the status permission of the phone -->

<Uses-permission android: name = "android. permission. READ_PHONE_STATE"/>

<! -- Recording permission -->

<Uses-permission android: name = "android. permission. RECORD_AUDIO"/>

<! -- SdCard read permission -->

<Uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/>

<! -- SdCard write permission -->

<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>

<! -- Open the network permission -->

<Uses-permission android: name = "android. permission. INTERNET"/>

 

 

Bind Local Service

Binding a local service is actually binding the activity and service. The activity usually interacts with the user, and the Service generally performs background work. If the activity needs to access some methods in the service, for interaction, You need to bind.

 

Ÿ bindService is used to bind services, and a custom ServiceConnection is passed in to receive IBinder

 

Define a business interface, which defines the required methods

 

In the rule service, you define an IBinder to inherit the Binder and implement the business interface. In the onBind method

 

The producer caller converts IBinder to an interface type, and calls the methods in the interface to call the methods in the service.

 

Example of Binding Activity and Service:

 

Activity:

 

 

Public class MainActivity extends Activity {

Private QueryService qs;

Private EditText editText;

 

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

EditText = (EditText) findViewById (R. id. id );

// Bind the service and pass in ServiceConnection to receive IBinder

BindService (new Intent (this, PersonService. class), new MyConn (), BIND_AUTO_CREATE );

}

 

/*

* Custom ServiceConnection is used to receive IBinder

*/

Private final class MyConn implements ServiceConnection {

Public void onServiceConnected (ComponentName name, IBinder service ){

Qs = (QueryService) service;

}

Public void onServiceDisconnected (ComponentName name ){

}

}

 

/*

* Obtain contacts by Id

*/

Public void queryName (View view ){

String id = editText. getText (). toString ();

String name = qs. query (Integer. parseInt (id ));

Toast. makeText (this, name, 0). show ();

}

}

Service:

 

 

Public class PersonService extends Service {

 

Private String [] data = {"zxx", "lhm", "flx "};

 

/* Www.2cto.com

* Call this method when binding. An IBinder is returned to call the method in the current service.

*/

Public IBinder onBind (Intent intent ){

Return new MyBinder ();

}

 

/*

* Query Method

*/

Public String query (int id ){

Return data [id];

}

 

/*

* Customizes the IBinder to implement the QueryService business interface and provides callers with methods to access the current service.

*/

Private final class MyBinder extends Binder implements QueryService {

Public String query (int id ){

Return PersonService. this. query (id );

}

}

 

}

 

 

 

Bind a remote service

The same interface cannot be used to call a method when the consumer is remotely bound to a service. In this case, the AIDL technology is required.

 

Modify the interface extension to ". aidl"

 

Revoke remove permission Modifier

 

The interface with the same name is generated in the Development gen folder.

 

Modify the custom IBinder class of the Service to the Stub class in the inherited interface.

 

The IBinder returned by Ÿ ServiceConnection is a proxy object and cannot be strongly converted. Use Stub. asInterface () instead. Excerpt from: Fu rongkang Column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.