需要的知识点:Notification、Service

第三方开源框架 : android-async-http-master

推送的来源:android项目中,有时会有这样一种需求:客户每隔一段时间,就像服务器发送一个请求,以获取某些重要的、实时更新的消息。比如版本更新,请求是否重新下载等。

关键点在于: 如何让应用实现在后台一直处于运行状态,并且每个一段时间就向服务器发一个请求?

一、在Activity中,通过startService()来启动服务

     public void open(View view) {

        Intent intent = new Intent(this, PushSmsService.class); //跳转页面 
        startService(intent);  // 启动服务  
    }
 
二、自定义一个服务类,去继承android的Service类
    /*******************************************************/
    //短信推送服务类,在后台长期运行,每个一段时间就向服务器发送一次请求 
    /*******************************************************/
   public class PushSmsService extends Service {

    private MyThread myThread; //线程  
    private NotificationManager manager;  //notificationManager  
    private Notification notification;  //notification
    private PendingIntent pi;  //intent
    private AsyncHttpClient client;  //异步http客户端
    private boolean flag = true;  //标志位为true
  
    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  
 
/****************************************< 加载页面 >******************************************/
   @Override

    public void onCreate() {  
        System.out.println("oncreate()");  
        this.client = new AsyncHttpClient();  
        this.myThread = new MyThread();  
        this.myThread.start();  //启动线程
        super.onCreate();  
    }  
 
    //销毁页面
    public void onDestroy() {

        this.flag = false; //标志位为:false  
        super.onDestroy();  
    }  
 
 
/****************************************< notification >******************************************/
    private void notification(String content, String number, String date) {

        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  // 获取系统的通知管理器  
        notification = new Notification(R.drawable.ic_menu_compose, content,   System.currentTimeMillis());  //获取图标、内容、时间等等
        notification.defaults = Notification.DEFAULT_ALL; // 使用默认设置(比如铃声、震动、闪灯)  
        notification.flags = Notification.FLAG_AUTO_CANCEL; // 但用户点击消息后,消息自动在通知栏自动消失  
        notification.flags |= Notification.FLAG_NO_CLEAR;// 点击通知栏的删除,消息不会依然不会被删除  
  
        Intent intent = new Intent(getApplicationContext(),   ContentActivity.class);  //跳转页面
        intent.putExtra("content", content);  //封装内容
        intent.putExtra("number", number);  //封装数字
        intent.putExtra("date", date);  //封装时间
  
        pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);           
        notification.setLatestEventInfo(getApplicationContext(), number  + "发来短信", content, pi);  
        manager.notify(0, notification);  // 将消息推送到状态栏  
       
/****************************************< 线程 >******************************************/
        private class MyThread extends Thread {

        public void run() {  
                 String url = "http://110.65.99.66:8080/jerry/PushSmsServlet";  //定位服务器
            while (flag) {//检查并判断标志位  
                System.out.println("发送请求");  
                try {                      
                    Thread.sleep(10000); // 每个10秒向服务器发送一次请求   
                } catch (InterruptedException e)
               {  
                    e.printStackTrace();  
                }  
  
                // 采用get方式向服务器发送请求  
                client.get(url, new AsyncHttpResponseHandler() {   
                    public void onSuccess(int statusCode, Header[] headers,  byte[] responseBody) {  
                        try {  
                            JSONObject result = new JSONObject(new String(  responseBody, "utf-8"));  
                            int state = result.getInt("state");  
                            // 假设偶数为未读消息  
                            if (state % 2 == 0) {  
                                String content = result.getString("content");  
                                String date = result.getString("date");  
                                String number = result.getString("number");  
                                notification(content, number, date);  
                            }  
                        } catch (Exception e) {  
                            e.printStackTrace();  
                        }   
                    }  
 
               public void onFailure(int statusCode, Header[] headers,   byte[] responseBody, Throwable error) {

                        Toast.makeText(getApplicationContext(), "数据请求失败", 0)  .show();  
                    }  
        });  
    }  
  
三、清单文件中注册
      3.1 service注册:
            <service android:name=".PushSmsService"></service>
四、权限配置问题
       4.1 由于通知信息使用到了手机的震动功能和网络访问,所以需要配置权限。
             <uses-permission android:name="android.permission.VIBRATE"/>  <!-震动权限->

             <uses-permission android:name="android.permission.INTERNET"/>  <!-网络权限->
五、再定义Activity
     (用于用户点击下拉通知栏里的某条消息后,跳转到详细的消息界面)
      public class ContentActivity extends Activity {

          protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_content);  
            Intent intent = getIntent();  
            TextView tv_content = (TextView) this.findViewById(R.id.tv_content);  
            TextView tv_number = (TextView) this.findViewById(R.id.tv_number);  
            TextView tv_date = (TextView) this.findViewById(R.id.tv_date);  
        if (intent != null) {  
            String content = intent.getStringExtra("content");  
            String number = intent.getStringExtra("number");  
            String date = intent.getStringExtra("date");  
            tv_content.setText("内容:" + content);  
            tv_number.setText("号码:" + number);  
            tv_date.setText("日期:" + date);  
        }   
    }  
  
    5.1 在清单文件中注册新的Activity
          <activity android:name=".ContentActivity"></activity> 
    5.2 注意到上边的代码是需要服务器提供支持的,我们去新建一个简单的服务器,里边添加一个Servlet和一个实体类就可以了
         public class PushSmsServlet extends HttpServlet {

         private static int index = 1;  
        public void doGet(HttpServletRequest request, HttpServletResponse response)  
              throws ServletException, IOException {  
              System.out.println(index);  
              // List<Sms> smsList = new ArrayList<Sms>();  
              Sms sms = new Sms(index,  "傻逼" + index, "2016-08-08",  "15208432222");  
              index++;  
             // smsList.add(sms);  
             // sms = new Sms(0, "傻逼", "2016-08-08", "15208432222");  
             // smsList.add(sms);  
             // sms = new Sms(1, "傻逼", "2016-08-08", "13522224444");  
             // smsList.add(sms);  
  
        response.setContentType("text/html");  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("utf-8");  
        PrintWriter out = response.getWriter();  
        Gson gson = new Gson();  
        // 将Sms类的数据转换为json数据格式  
        String json = gson.toJson(sms);  
        out.write(json);  
        out.flush();  
        out.close();  
    }  
 
       //doPost
        public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {

           this.doGet(request, response);  
       }
     
/****************************************< 定义封装用于存放消息的类 >******************************************/    

public class Sms {

    private int state;  
    private String content;  
    private String date;  
    private String number;  
  
    public Sms(int state, String content, String date, String number) {  
        super();  
        this.state = state;  
        this.content = content;  
        this.date = date;  
        this.number = number;  
    }    
 
这部只是分核心代码,其余的就请自行扩充!

Android开发--推送的更多相关文章

  1. Android消息推送怎么实现?

    在开发Android和iPhone应用程序时,我们往往需要从服务器不定的向手机客户端即时推送各种通知消息,iPhone上已经有了比较简单的和完美的推送通知解决方案,可是Android平台上实现起来却相 ...

  2. Android实现推送方式解决方案(转)

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  3. Android消息推送完美方案[转]

    转自 Android消息推送完美方案 推送功能在手机应用开发中越来越重要,已经成为手机开发的必须.在Android应用开发中,由于众所周知的原因,Android消息推送我们不得不大费周折.本文就是用来 ...

  4. Android消息推送完美方案

    转自:http://bbs.hiapk.com/thread-4652657-1-1.html 推送功能在手机应用开发中越来越重要,已经成为手机开发的必须.在Android应用开发中,由于众所周知的原 ...

  5. Android消息推送完美解决方案全析

    推送功能在手机应用开发中越来越重要,已经成为手机开发的必须.在Android应用开发中,由于众所周知的原因,Android消息推送我们不得不大费周折.本文就是用来和大家共同探讨一种Android消息推 ...

  6. Android消息推送(二)--基于MQTT协议实现的推送功能

    国内的Android设备,不能稳定的使用Google GCM(Google Cloud Messageing)消息推送服务. 1. 国内的Android设备,基本上从操作系统底层开始就去掉了Googl ...

  7. 【转】Android实现推送方式解决方案

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  8. Android实现推送方式解决方案 - 长连接+心跳机制(MQTT协议)

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  9. android 消息推送

    android 消息推送 极光推送百度云推送(语音)友盟消息推送

随机推荐

  1. Light OJ 1032 - Fast Bit Calculations(数位DP)

    题目大意: 一个数字把他看成二进制数字,数字里又会一些相邻的1,问从0到n至间所有相邻1的总和是多少?   分解成2进制数字,然后数位DP就行了.   ======================== ...

  2. 【转】Android ProgressDialog的使用2

    原文网址:http://www.cnblogs.com/hnrainll/archive/2012/03/28/2420908.html <?xml version="1.0" ...

  3. 启动tomcat的 startup.bat屏幕一闪而过

    有时启动tomcat 时,屏幕一闪而过,看不到是那里有问题.要想让屏幕停下来,做法如下: 1.打开 startup.bat 文件,在文件最后加上最后加一行@pause 2.重新运行 startup.b ...

  4. HDU-4920 Matrix multiplication

    矩阵相乘,采用一行的去访问,比采用一列访问时间更短,根据数组是一行去储存的.神奇小代码. Matrix multiplication Time Limit: 4000/2000 MS (Java/Ot ...

  5. linux安装JDK TOMCAT

    1.下载包 到http://apr.apache.org/下载下面3个包 apr-1.4.2.tar.gz apr-iconv-1.2.1.tar.gz apr-util-1.3.10.tar.gz  ...

  6. 把测试app打包成ipa文件

    我终于把我的程序放到我的touch上了,其实把app放到touch上还有很多办法,这篇教程是主要讲怎么把app注册了,然后打包成一个ipa文件的. 先上官方文档:https://developer.a ...

  7. Delegate。。

    Delegate类简介------------------------ 命名空间:System程序集:mscorlib(在 mscorlib.dll 中) 委托(Delegate)类是一种数据结构,通 ...

  8. Centos6.4 cobbler安装要点

    1,yum 安装cobbler rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm y ...

  9. django运行django-admin.py无法创建网站

    安装django的步骤: 1.安装python,选择默认安装在c盘即可.设置环境变量path,值添加python的安装路径. 2.下载ez_setup.py,下载地址:http://peak.tele ...

  10. Struct2 向Action中传递参数(中文乱码问题)

    就是把视图上的值传递到Action定义的方法中 也就是把数据从前台传递到后台 三种方式: 1.  使用action属性接收参数 比如jsp页面: <body> 使用action属性接收参数 ...