notification+service实现消息推送

Activity

public class NotificationActivity extends Activity { 

 @Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_notification);

 }

 public void open(View view) {

  Intent intent = new Intent(this, PushSmsService.class);

  // 启动服务

  startService(intent);

 }

 public void close(View view) {

  Intent intent = new Intent(this, PushSmsService.class);

  // 停止服务

  stopService(intent);

 }

}


PushSmsService 

/** 

 *

 * 短信推送服务类,在后台长期运行,每个一段时间就向服务器发送一次请求

 *

 * @author jerry

 *

 */

public class PushSmsService extends Service {

 private MyThread myThread;

 private NotificationManager manager;

 private Notification notification;

 private PendingIntent pi;

 private AsyncHttpClient client;

 private boolean flag = true;

 @Override

 public IBinder onBind(Intent intent) {

  // TODO Auto-generated method stub

  return null;

 }

 @Override

 public void onCreate() {

  System.out.println("oncreate()");

  this.client = new AsyncHttpClient();

  this.myThread = new MyThread();

  this.myThread.start();

  super.onCreate();

 }

 @Override

 public void onDestroy() {

  this.flag = false;

  super.onDestroy();

 }

 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 {

  @Override

  public void run() {

   String url = "http://110.65.99.66:8080/jerry/PushSmsServlet";

   while (flag) {

    System.out.println("发送请求");

    try {

     // 每个10秒向服务器发送一次请求

     Thread.sleep(10000);

    } catch (InterruptedException e) {

     e.printStackTrace();

    }

    // 采用get方式向服务器发送请求

    client.get(url, new AsyncHttpResponseHandler() {

     @Override

     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();

      }

     }

     @Override

     public void onFailure(int statusCode, Header[] headers,

       byte[] responseBody, Throwable error) {

      Toast.makeText(getApplicationContext(), "数据请求失败", 0)

        .show();

     }

    });

   }

  }

 }

}

ContentActivity 

public class ContentActivity extends Activity { 

 @Override

 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);

  }

 }

}

Manifest

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

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

    package="cn.itcast.notification"

    android:versionCode="1"

    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="10"

        android:targetSdkVersion="10" />

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

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

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="cn.itcast.notification.NotificationActivity"

            android:label="@string/app_name" >

            <intent-filter>

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

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

            </intent-filter>

        </activity>

        <activity android:name=".ContentActivity"></activity>

        <service android:name=".PushSmsService"></service>

    </application>

</manifest>

服务器代码

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, "2013-03-03",

    "13522224444");

  index++;

  // smsList.add(sms);

  // sms = new Sms(0, "我真的爱你", "2013-04-04", "13522224444");

  // smsList.add(sms);

  // sms = new Sms(1, "我真的真的爱你", "2013-05-05", "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();

 }

 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;

 }

}

原文地址:https://www.cnblogs.com/freenovo/p/4469809.html