package com.tokudu.demo;
import java.io.IOException;
import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttPersistence;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
/*
* PushService that does all of the work.
* Most of the logic is borrowed from KeepAliveService.
* http://code.google.com/p/android-random/source/browse/trunk/TestKeepAlive/src/org/devtcg/demo/keepalive/KeepAliveService.java?r=219
*/
public class PushService extends Service {
// this is the log tag
public static final String TAG = "DemoPushService";
// the IP address, where your MQTT broker is running.
// private static final String MQTT_HOST = "192.168.1.71";
private static final String MQTT_HOST = "192.168.36.215";
// private static final String MQTT_HOST = "192.168.1.190";
// the port at which the broker is running.
private static int MQTT_BROKER_PORT_NUM = 1883;
// Let's not use the MQTT persistence.
private static MqttPersistence MQTT_PERSISTENCE = null;
// We don't need to remember any state between the connections, so we use a
// clean start.
private static boolean MQTT_CLEAN_START = true;
// Let's set the internal keep alive for MQTT to 15 mins. I haven't tested
// this value much. It could probably be increased.
private static short MQTT_KEEP_ALIVE = 60 * 15;
// Set quality of services to 0 (at most once delivery), since we don't want
// push notifications
// arrive more than once. However, this means that some messages might get
// lost (delivery is not guaranteed)
private static int[] MQTT_QUALITIES_OF_SERVICE = { 0 };
private static int MQTT_QUALITY_OF_SERVICE = 0;
// The broker should not retain any messages.
private static boolean MQTT_RETAINED_PUBLISH = false;
// MQTT client ID, which is given the broker. In this example, I also use
// this for the topic header.
// You can use this to run push notifications for multiple apps with one
// MQTT broker.
public static String MQTT_CLIENT_ID = "tokudu";
// These are the actions for the service (name are descriptive enough)
private static final String ACTION_START = MQTT_CLIENT_ID + ".START";
private static final String ACTION_STOP = MQTT_CLIENT_ID + ".STOP";
private static final String ACTION_KEEPALIVE = MQTT_CLIENT_ID
+ ".KEEP_ALIVE";
private static final String ACTION_RECONNECT = MQTT_CLIENT_ID
+ ".RECONNECT";
// Connection log for the push service. Good for debugging.
private ConnectionLog mLog;
// Connectivity manager to determining, when the phone loses connection
private ConnectivityManager mConnMan;
// Notification manager to displaying arrived push notifications
private NotificationManager mNotifMan;
// Whether or not the service has been started.
private boolean mStarted;
// This the application level keep-alive interval, that is used by the
// AlarmManager
// to keep the connection active, even when the device goes to sleep.
private static final long KEEP_ALIVE_INTERVAL = 1000 * 60 * 28;
// Retry intervals, when the connection is lost.
private static final long INITIAL_RETRY_INTERVAL = 1000 * 10;
private static final long MAXIMUM_RETRY_INTERVAL = 1000 * 60 * 30;
// Preferences instance
private SharedPreferences mPrefs;
// We store in the preferences, whether or not the service has been started
public static final String PREF_STARTED = "isStarted";
// We also store the deviceID (target)
public static final String PREF_DEVICE_ID = "deviceID";
// We store the last retry interval
public static final String PREF_RETRY = "retryInterval";
// Notification title
public static String NOTIF_TITLE = "Tokudu";
// Notification id
private static int NOTIF_CONNECTED = 0;
// This is the instance of an MQTT connection.
private MQTTConnection mConnection;
private long mStartTime;
// Static method to start the service
public static void actionStart(Context ctx) {
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
// Static method to stop the service
public static void actionStop(Context ctx) {
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_STOP);
ctx.startService(i);
}
// Static method to send a keep alive message
public static void actionPing(Context ctx) {
Intent i = new Intent(ctx, PushService.class);
i.setAction(ACTION_KEEPALIVE);
ctx.startService(i);
}
@Override
public void onCreate() {
super.onCreate();
log("Creating service");
mStartTime = System.currentTimeMillis();
try {
mLog = new ConnectionLog();
Log.i(TAG, "Opened log at " + mLog.getPath());
} catch (IOException e) {
Log.e(TAG, "Failed to open log", e);
}
// Get instances of preferences, connectivity manager and notification
// manager
mPrefs = getSharedPreferences(TAG, MODE_PRIVATE);
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
mNotifMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/*
* If our process was reaped by the system for any reason we need to
* restore our state with merely a call to onCreate. We record the last
* "started" value and restore it here if necessary.
*/
handleCrashedService();
}
// This method does any necessary clean-up need in case the server has been
// destroyed by the system
// and then restarted
private void handleCrashedService() {
if (wasStarted() == true) {
log("Handling crashed service...");
// stop the keep alives
stopKeepAlives();
// Do a clean start
start();
}
}
@Override
public void onDestroy() {
log("Service destroyed (started=" + mStarted + ")");
// Stop the services, if it has been started
if (mStarted == true) {
stop();
}
try {
if (mLog != null)
mLog.close();
} catch (IOException e) {
}
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
log("Service started with intent=" + intent);
// Do an appropriate action based on the intent.
if (intent.getAction().equals(ACTION_STOP) == true) {
stop();
stopSelf();
} else if (intent.getAction().equals(ACTION_START) == true) {
start();
} else if (intent.getAction().equals(ACTION_KEEPALIVE) == true) {
keepAlive();
} else if (intent.getAction().equals(ACTION_RECONNECT) == true) {
if (isNetworkAvailable()) {
reconnectIfNecessary();
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
// log helper function
private void log(String message) {
log(message, null);
}
private void log(String message, Throwable e) {
if (e != null) {
Log.e(TAG, message, e);
} else {
Log.i(TAG, message);
}
if (mLog != null) {
try {
mLog.println(message);
} catch (IOException ex) {
}
}
}
// Reads whether or not the service has been started from the preferences
private boolean wasStarted() {
return mPrefs.getBoolean(PREF_STARTED, false);
}
// Sets whether or not the services has been started in the preferences.
private void setStarted(boolean started) {
mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
mStarted = started;
}
private synchronized void start() {
log("Starting service...");
// Do nothing, if the service is already running.
if (mStarted == true) {
Log.w(TAG, "Attempt to start connection that is already active");
return;
}
// Establish an MQTT connection
connect();
// Register a connectivity listener
registerRece
没有合适的资源?快使用搜索试试~ 我知道了~
AndroidPushNotificationsDemo
共46个文件
class:19个
java:6个
xml:5个
5星 · 超过95%的资源 需积分: 10 125 下载量 191 浏览量
2015-01-19
23:37:39
上传
评论 2
收藏 237KB RAR 举报
温馨提示
MQTT协议是为大量计算能力有限,且工作在低带宽、不可靠的网络的远程传感器和控制设备通讯而设计的协议,它具有以下主要的几项特性: 1、使用发布/订阅消息模式,提供一对多的消息发布,解除应用程序耦合; 2、对负载内容屏蔽的消息传输; 3、使用 TCP/IP 提供网络连接; 4、有三种消息发布服务质量: “至多一次”,消息发布完全依赖底层 TCP/IP 网络。会发生消息丢失或重复。这一级别可用于如下情况,环境传感器数据,丢失一次读记录无所谓,因为不久后还会有第二次发送。 “至少一次”,确保消息到达,但消息重复可能会发生。 “只有一次”,确保消息到达一次。这一级别可用于如下情况,在计费系统中,消息重复或丢失会导致不正确的结果。 5、小型传输,开销很小(固定长度的头部是 2 字节),协议交换最小化,以降低网络流量; 6、使用 Last Will 和 Testament 特性通知有关各方客户端异常中断的机制;
资源推荐
资源详情
资源评论
收起资源包目录
AndroidPushNotificationsDemo.rar (46个子文件)
AndroidPushNotificationsDemo
AndroidPushNotificationsDemo
bin
classes.dex 112KB
res
crunch
drawable
icon.png 1KB
logo.png 10KB
AndroidPushNotificationsDemo.apk 54KB
dexedLibs
annotations-b4c040bad048c9dd4c5c151b69a8b6ff.jar 910B
wmqtt-43d25cf1cabc43d16e4789b001822b79.jar 27KB
classes
com
tokudu
demo
ConnectionLog.class 2KB
BuildConfig.class 339B
PushService.class 12KB
R$layout.class 385B
R$id.class 558B
R$drawable.class 419B
PushActivity$1.class 2KB
PushActivity.class 2KB
R$attr.class 331B
R.class 555B
ConnectServerTask$1.class 2KB
PushActivity$2.class 1KB
PushService$1.class 2KB
ConnectServerTask$ConnectionCallBack.class 285B
ConnectServerTask.class 10KB
R$string.class 550B
ConnectServerTask$MQTTConnection.class 6KB
R$color.class 428B
PushService$MQTTConnection.class 4KB
resources.ap_ 15KB
AndroidManifest.xml 1KB
res
drawable-ldpi
drawable-hdpi
drawable-xhdpi
drawable
icon.png 1KB
logo.png 10KB
values
colors.xml 151B
strings.xml 380B
drawable-mdpi
layout
main.xml 2KB
assets
gen
com
tokudu
demo
BuildConfig.java 157B
R.java 1KB
.settings
org.eclipse.jdt.core.prefs 177B
src
com
tokudu
demo
PushService.java 17KB
PushActivity.java 2KB
ConnectionLog.java 2KB
ConnectServerTask.java 15KB
README 123B
.project 831B
.classpath 528B
.gitignore 12B
project.properties 647B
AndroidManifest.xml 1KB
libs
wmqtt.jar 47KB
共 46 条
- 1
资源评论
- zhr2017-02-14非常不错的mqtt学习demo,可以正常运行
- sadassdasd2015-07-31现在比较流行的推送方式,研究研究
- 80的夏夜2015-02-10现在比较流行的推送方式,研究研究
- 小猫太郎2020-02-12资源不错,可以使用
- gzuguo2015-03-01看不懂,不过貌似很厉害的样子
slimina
- 粉丝: 421
- 资源: 67
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功