Android采用服务执行长期后台的操作

                                                                                      采用服务执行长期后台的操作

写一个用户监听用户的手机通话状态的软件

package com.example.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;

public class Myservice extends Service{
	/**
	 * 服务是长期在后台运行的组件,如果用户不手动关闭,是不会停止的
	 */

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("服务被开启");
		//监视用户电话状态的变化
		//电话管理服务
		TelephonyManager telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		//监听手机的通话状态
		telManager.listen(new ListenCallState(), PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("服务被销毁");
	}
	private class ListenCallState extends PhoneStateListener{
		/**
		 * 手机的电话状态被改变的时候进行调用
		 */

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE://空闲状态,没有通话,没有响铃
				
				break;
			case TelephonyManager.CALL_STATE_RINGING://响铃状态
				System.out.println("发现来电号码:"+incomingNumber);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK://通话状态
				System.out.println("电话处于通话状态");
				break;

			default:
				break;
			}
		}

		
		
	}
	

}
清单文件:
   <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.service.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.example.service.Myservice"></service>
    </application>



你可能感兴趣的:(Android采用服务执行长期后台的操作)