技术开发 频道

PendingInent 与 AlarmManager

  四、PendingInent与 service

  在OPhone系统编程中,一个完整OPhone应用程序可以有4个需要创建的模块,他们分别是:

  Activity ,Broadcast intent Receiver,Service,Content Provider。Service作为一个OPhone应用程序组成部分,通常运行在系统后台,他与用户之间没有交互。像其他应用程序对象一样运行在所属进程的主线程中。那么这就意味着它有可能进入长时间的运行等待而导致应用得不到用户的相应。所以在开发者设计程序的时候就要考虑,如果一个Service 要做一些长时间的数据处理时(比如播放MP3,或者是网络下载),就需要把该工作切换到自己的线程空间来执行。

  实例代码如下:

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.Toast;

//定义一个 Service 对象
public class AlarmService_Service extends Service {
    NotificationManager mNM;
    
public void onCreate() {
        
//创建一个线程来运行Runnable
        Thread thr
= new Thread(null, mTask, "AlarmService_Service");
        thr.start();
    }
    
public void onDestroy() {
    }
    Runnable mTask
= new Runnable() {
        
public void run() {
            
// 通常我们就可以在这里设计长时间运行的功能,
            
long endTime = System.currentTimeMillis() + 15*1000;
            
while (System.currentTimeMillis() < endTime) {
                synchronized (mBinder) {
                    try {
                        mBinder.wait(endTime
- System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }

            
// 停止Service
            AlarmService_Service.this.stopSelf();
        }
    };

    
//在编写Service代码时,可以不实现onStart,onStop等函数,但一定要实现onBind函数
    
public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
/*  通过该对象可以与客户端通信
    
*/
    
private final IBinder mBinder = new Binder() {
        @Override
        protected
boolean onTransact(int code, Parcel data, Parcel reply,
                
int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };
}

   小结:本篇文章主要介绍了如何使用AlarmManager的定时唤醒功能,以及各种闹铃的含义与API使用实例,希望对读者朋友们在OPhone应用编程中,对AlarmManager的正确使用起到抛砖引玉的作用。同时我们还引入了一个重要的概念 PendingIntent,通过对PendingIntent参数的解析,相信读者朋友们对PendingIntent的使用有了一个基本的认识。

0
相关文章