Android Four Components Service (service) examples of detailed _android

Source: Internet
Author: User
Tags inheritance prepare stub

This example describes the service usage of the four Android components. Share to everyone for your reference, specific as follows:

In many cases, some applications that have little interaction with the user, we typically have them run in the background, and we can still run other applications while they are running.

To handle this background process, Android introduces the concept of service. Service is a long life cycle component in Android that does not implement any user interface.

Basic concepts

Ÿservice is a component that runs in the background with no interface, starting with other component calls.
Y Create service, define class inheritance Service,androidmanifest.xml definition <service>
Y to turn on the service and invoke the StartService method in other components
Y Stop the service and call the StopService method

1. Invoking service in activity


 * * Open 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 {
   * * * bind timed
   call
  /public IBinder onbind (Intent Intent) {
    return null;
  }
   * * Call/public
  void OnCreate () {
    super.oncreate ()
    when opening the service; System.out.println ("OnCreate");
  }
   * * To end the service call/public
  void OnDestroy () {
    Super.ondestroy ();
    System.out.println ("OnDestroy");
  }


3. Define the service in the manifest file :

Copy Code code as follows:
<service android:name= ". Pmyservice "/>

Telephone recording

Telephone recordings are implemented using services, running in the background, using the listener to monitor the status of the phone, when the phone calls, the listener gets the phone number of the arrival call, when the user answered, began recording, when the monitor heard the status of the phone hanging, stop recording, and the recording to save to the SDcard.

Java code:

@Override public void OnCreate () {//Get phone service Telephonymanager manager = (Telephonymanager) getsystemservice (context.te
  Lephony_service);
The status of the telephone 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 states, String incomingnumber) {switch (state) {//Bell status case telephonym Anager.
        Call_state_ringing://save telephone number num = Incomingnumber;
      Break Connect phone status Case TelephonyManager.CALL_STATE_OFFHOOK:try {//Set file save location files = new file (Envi
          Ronment.getexternalstoragedirectory (), num + "_" + system.currenttimemillis () + ". 3gp");
          Create a recording device recorder = new Mediarecorder ();
          Set the source of the audio (microphone) Recorder.setaudiosource (audiosource.mic); Take the 3GP format to save Recorder.setoutputformat (OUTPUTFORMAT.THREE_GPP);
          Setting 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; Phone Idle status Case telephonymanager.call_state_idle://Phone hang up stop recording if (recorder!= null) {record
          Er.stop ();
        Recorder.release ();
    } break;

 }
  }
}

Permissions:

<!--read the status of the phone-->
<uses-permission android:name= "Android.permission.READ_PHONE_STATE"/>
<! --Recording Permissions-->
<uses-permission android:name= "Android.permission.RECORD_AUDIO"/>
<!--sdcard Read permissions- ->
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- SDcard Write permissions-->
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
< !--Turn on network permissions-->
<uses-permission android:name= "Android.permission.INTERNET"/>

The service of the land binding

Binding the service is actually the activity and the service to bind, activities are generally interacting with the user, and the service is generally in the background of the work, if you need to access the service in some methods, to interact, this requires binding.

Y uses the Bindservice binding service to pass a custom serviceconnection to receive the IBinder
Y defines a business interface that defines the methods that need to be used
The Y service customizes a IBinder inheritance binder and implements the business interface, returning in the Onbind method
The Y caller converts ibinder to an interface type, and calls methods in the interface to call methods in the service

Examples 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 service, incoming serviceconnection to receive IBinder
    Bindservice (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) {
    }
  }
  /
   * * Get contact
  based on 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"};
   * * When binding calls this method, returns a IBinder to invoke the method in the current service
   /public
  ibinder onbind (Intent Intent) {return
    new Mybinder ();
  }
   * * * Query method *
  /public String query (int id) {return
    data[id];
  }
   * * Custom IBinder, implement QueryService business interface, provide the caller with the means to access the current service
   * *
  Private Final class Mybinder extends Binder Implements QueryService {public
    String query (int id) {return
      PersonService.this.query (ID);
    }
}

Binding Remote Services

Y you cannot invoke a method by using the same interface when you remotely bind a service, you need to use the AIDL technique
Y change the interface extension to ". Aidl"
Y Remove the permission modifier
An interface with the same name is generated under the Ÿgen folder
Y Changes the custom IBinder class in the service to the stub in the inheritance interface
The IBinder returned in Ÿserviceconnection is a proxy object and cannot be used with a strong turn, instead of Stub.asinterface ()

I hope this article will help you with the Android program.

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.