码迷,mamicode.com
首页 > 移动开发 > 详细

Android开发:利用AlarmManager不间断向服务器发送请求以及notification通知

时间:2016-05-30 14:55:07      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

一.前言

嗯,其实需求很简单,但是因为服务器不会主动联系客户端,所以客户端必须不间断的向服务器请求以便得到一些数据,突然不知道怎么描述这个问题了,总之,我是通过AlarmManager来实现客户端不断地向服务器发送请求,好吧,往下。

二.实现

客户端不断的发请求,然后通过获得的响应做一些处理就可以了,流程就简简单单的像下面这个图。
技术分享

第一步:利用AlarmManager开启轮询服务

public class MyAlarmManager
{
 //开启轮询服务
    public static void startPollingService(Context context, int seconds, Class<?> cls,String carUserId) {
        //获取AlarmManager系统服务
        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Log.e("startPollingService:","开启轮询服务");
        Intent intent = new Intent(context, cls);
        intent.putExtra("carUserId",carUserId);//添加需要传递的一些参数
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);//我是用的是service
        //使用AlarmManger的setRepeating方法设置定期执行的时间间隔(seconds秒)和需要执行的Service
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), seconds * 1000, pendingIntent);

    }

    //停止轮询服务
    public static void stopPollingService(Context context, Class<?> cls,String action) {
        AlarmManager manager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //取消正在执行的服务
        manager.cancel(pendingIntent);
    }
}

第二步:Service/BroadcastReceiver/Activity完成相应的请求

我使用的是Service

/**
 *轮询服务
 *使用notification弹出消息
 */
public class QueryUnusualService extends Service {

    private Notification notification;
    private NotificationManager manager;
    private Handler handler;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what)
                {
                    case R.id.query_unusual_car_result:
                        List<Map<String,Object>> unusualCarList = (List<Map<String,Object>>)msg.getData().getSerializable("unusualCarList");
                        if(unusualCarList==null||unusualCarList.size()<1)
                            return;
                        showNotification(unusualCarList);
                        break;
                    default:
                        break;
                }
            }
        };
    }
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        //请求数据        
        CarController.queryUnusualCar(intent.getStringExtra("carUserId"), handler);
    }
    //弹出Notification
    private void showNotification(List<Map<String,Object>> unusualCarList) {
        final Bitmap largeIcon = ((BitmapDrawable) getResources().getDrawable(R.drawable.stefan)).getBitmap();
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0, new Intent().setAction("intvehapp.intvehapp.Activity.BaiDuMapActivity"), 0);
        notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.head_image)
                .setLargeIcon(largeIcon)
                .setTicker("新消息!!")
                .setContentTitle("新消息!!!!")
                .setContentText("新消息~")
                .setContentIntent(pendingIntent3).setNumber(1).getNotification(); // 需要注意build()是在API
        // level16及之后增加的,API11可以使用getNotificatin()来替代
        notification.flags |= Notification.FLAG_AUTO_CANCEL; // FL
        manager.notify(1, notification);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service:onDestroy");
    }
}

大功告成

三.问题

大家在开发的过程中可能会发现一些问题,比如
1.不间断轮询失败
这里一定要注意 manager.setRepeating()的参数,特别是第一个参数和第二个参数相对应,即关于闹铃的类型问题:

//一共有五种闹铃类型:
    public static final int ELAPSED_REALTIME  
    //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3    (0x00000003)。  
    public static final int ELAPSED_REALTIME_WAKEUP      //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002)  
    ublic static final int RTC  
    //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用 System.currentTimeMillis()获得。系统值是1 (0x00000001) 。
    public static final int RTC_WAKEUP  
    //能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。  
    Public static final int POWER_OFF_WAKEUP  
    //能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为4(0x00000004)。     

2.Notification不提示消息的问题
1).请设置icon
2).如果API是16请将getNotification()换成build()

Android开发:利用AlarmManager不间断向服务器发送请求以及notification通知

标签:

原文地址:http://blog.csdn.net/chentravelling/article/details/51532888

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!