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;
import com.tokudu.demo.SystemApplication;
/*
* 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 = "59.125.190.113";
// 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 = "heran";
// 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 final 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
没有合适的资源?快使用搜索试试~ 我知道了~
MQTT的Demo展示
共42个文件
class:17个
java:6个
xml:5个
2星 需积分: 9 27 下载量 149 浏览量
2015-12-26
17:37:49
上传
评论
收藏 221KB RAR 举报
温馨提示
MQTT的範例檔案,Android版本,若有問題歡迎來信提問,一定幫你解決問題的。
资源推荐
资源详情
资源评论
收起资源包目录
AndroidPushNotificationsDemo.rar (42个子文件)
AndroidPushNotificationsDemo
wmqtt.jar 47KB
.project 831B
project.properties 648B
src
com
tokudu
demo
ConnectionLog.java 2KB
SystemApplication.java 225B
PushActivity.java 3KB
PushService.java 17KB
AndroidManifest.xml 1KB
res
drawable
icon.png 1KB
logo.png 10KB
layout
main.xml 3KB
values
colors.xml 151B
strings.xml 380B
gen
com
tokudu
demo
BuildConfig.java 157B
R.java 2KB
.classpath 539B
.gitignore 12B
README 123B
bin
resources.ap_ 16KB
AndroidPushNotificationsDemo.apk 53KB
classes
com
tokudu
demo
R$layout.class 385B
PushService$1.class 2KB
BuildConfig.class 339B
R$drawable.class 419B
R$attr.class 331B
PushActivity.class 3KB
PushActivity$2.class 1KB
SystemApplication.class 516B
R$id.class 650B
PushActivity$1.class 2KB
ConnectionLog.class 2KB
R.class 555B
R$string.class 550B
PushService$MQTTConnection.class 4KB
PushService.class 12KB
R$color.class 428B
PushActivity$3.class 2KB
AndroidManifest.xml 1KB
dexedLibs
wmqtt-0c3bb050e0da70f39c39c73f9fa1bd07.jar 28KB
res
crunch
drawable
icon.png 1KB
logo.png 10KB
classes.dex 87KB
共 42 条
- 1
资源评论
- 草木灰—CRL2015-12-29一般般,自己学习
github_23243937
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- DatabaseWatermarkingBasedonTextFormat
- -移动通信-网络课程设计与研究
- 基于Python的PCA人脸识别算法的原理及实现代码+文档详解.zip
- 甘肃移动全业务工程建设项目管理流程优化研究
- 549springboot + vue 民宿管理平台.zip (可运行源码+数据库文件+文档)
- ZArchiver.Pro_0.9.5.apk
- vmware环境配置.mp4
- 548springboot + vue 大学生社团活动平台.zip(可运行源码+数据库文件+文档)
- 微信小程序 辩论倒计时小程序源码 作业设计demo 计算机专业参考
- 深入探究文件IO,嵌入式Linux
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功