Android后台服务和唤醒锁
我有android后台服务来连接我的RabbitMQ服务器。我的后台服务侦听传入的rabbitmq消息。一切正常,但问题是在屏幕关闭时出现的。我的android客户端在手机屏幕关闭时断开连接。我应该怎么做才能始终与我的android rabbitmq客户端和rabbitmq服务器连接 我的代码如下:Android后台服务和唤醒锁,android,service,background,Android,Service,Background,我有android后台服务来连接我的RabbitMQ服务器。我的后台服务侦听传入的rabbitmq消息。一切正常,但问题是在屏幕关闭时出现的。我的android客户端在手机屏幕关闭时断开连接。我应该怎么做才能始终与我的android rabbitmq客户端和rabbitmq服务器连接 我的代码如下: public class RabbitmqPushService extends Service{ private Thread subscribeThread; private Connecti
public class RabbitmqPushService extends Service{
private Thread subscribeThread;
private ConnectionFactory factory;
private Connection connectionSubscribe;
private Channel channelSubscribe;
private NotificationManager mNotificationManager;
public static int NOTIFICATION_ID = 0;
private static final String HOST_NAME = Constant.HOST_NAME; //Rabbitmq Host Name
private static final int PORT_ADDRESS = 5672;
private static final String EXCHANGE_NAME = "fanout_msg";
private static String QUEUE_NAME = Constant.phone_number+"_queue"; //Queue Name
private static String[] ROUTE_KEY = {"all", Constant.phone_number};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
NOTIFICATION_ID = 0;
setupConnectionFactory();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(connectionSubscribe != null)
{
if(!connectionSubscribe.isOpen())
{
connect();
}
}
else
{
connect();
}
return Service.START_STICKY;
}
@Override
public void onDestroy() {
if(connectionSubscribe != null)
{
disconnectSubscribe();
}
NOTIFICATION_ID = 0;
}
private void setupConnectionFactory() {
factory = new ConnectionFactory();
factory.setHost(HOST_NAME);
factory.setPort(PORT_ADDRESS);
factory.setUsername(Constant.USERNAME);
factory.setPassword(Constant.PASSWORD);
factory.setRequestedHeartbeat(60);
}
private void connect()
{
final Handler incomingMessageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String message = msg.getData().getString("msg");
try {
JSONObject jsonObject = new JSONObject(message);
BeepHelper.msgBeep(getApplicationContext());
sendNotification("From : " + jsonObject.getString("from"), jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
};
subscribe(incomingMessageHandler);
publishToAMQP();
}
private void disconnectSubscribe()
{
subscribeThread.interrupt();
try {
channelSubscribe.close();
connectionSubscribe.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (TimeoutException e) {
e.printStackTrace();
}
}
void subscribe(final Handler handler)
{
subscribeThread = new Thread()
{
@Override
public void run() {
while(true) {
try {
connectionSubscribe = factory.newConnection();
channelSubscribe = connectionSubscribe.createChannel();
channelSubscribe.exchangeDeclare(EXCHANGE_NAME, "fanout");
channelSubscribe.queueDeclare(QUEUE_NAME, true, false, false, null);
for(int i = 0; i<ROUTE_KEY.length; i++)
{
channelSubscribe.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTE_KEY[i]);
}
QueueingConsumer consumer = new QueueingConsumer(channelSubscribe);
channelSubscribe.basicConsume(QUEUE_NAME, false, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("msg", message);
msg.setData(bundle);
handler.sendMessage(msg);
channelSubscribe.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
} catch (InterruptedException e) {
break;
} catch (Exception e1) {
try {
Thread.sleep(4000); //sleep and then try again
} catch (InterruptedException e) {
break;
}
}
}
}
};
subscribeThread.start();
}
@Override
public void publishMessage(String message) {
try {
queue.putLast(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void sendNotification(String title, String msg) {
mNotificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID++, mBuilder.build());
}
公共类RabbitmqPushService扩展服务{
私有线程读取;
私人连接工厂;
专用连接订阅;
专用信道信道订阅;
私人通知经理通知经理;
公共静态int通知_ID=0;
私有静态最终字符串HOST\u NAME=Constant.HOST\u NAME;//Rabbitmq主机名
专用静态最终int端口地址=5672;
私有静态最终字符串交换\u NAME=“fanout\u msg”;
私有静态字符串队列\u NAME=常量。电话号码+“\u队列”;//队列名称
私有静态字符串[]ROUTE_KEY={“all”,常量.phone_number};
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
通知_ID=0;
setupConnectionFactory();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
if(connectionSubscribe!=null)
{
如果(!connectionSubscribe.isOpen())
{
connect();
}
}
其他的
{
connect();
}
return Service.START\u STICKY;
}
@凌驾
公共空间{
if(connectionSubscribe!=null)
{
断开订阅();
}
通知_ID=0;
}
私有void setupConnectionFactory(){
工厂=新连接工厂();
factory.setHost(主机名);
工厂设置端口(端口地址);
factory.setUsername(常量.USERNAME);
出厂设置密码(常量密码);
factory.setRequestedHeartbeat(60);
}
专用void connect()
{
最终处理程序incomingMessageHandler=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
String message=msg.getData().getString(“msg”);
试一试{
JSONObject JSONObject=新的JSONObject(消息);
msgBeep(getApplicationContext());
sendNotification(“发件人:”+jsonObject.getString(“发件人”)、jsonObject.getString(“消息”);
}捕获(JSONException e){
e、 printStackTrace();
}
}
};
订阅(incomingMessageHandler);
publishToAMQP();
}
私有void disconnectSubscribe()
{
subscribeThread.interrupt();
试一试{
channelSubscribe.close();
connectionSubscribe.close();
}捕获(IOE异常){
e、 printStackTrace();
}
捕获(超时异常e){
e、 printStackTrace();
}
}
无效订阅(最终处理程序)
{
subscribeThread=新线程()
{
@凌驾
公开募捐{
while(true){
试一试{
connectionSubscribe=factory.newConnection();
channelSubscribe=connectionSubscribe.createChannel();
channelSubscribe.ExchangeClare(交换名称,“扇出”);
channelSubscribe.queueDeclare(队列名称,true、false、false、null);
对于(int i=0;i您需要一个唤醒锁,以便在屏幕关闭时保持手机运行。唤醒锁允许您的应用程序控制主机设备的电源状态
将唤醒锁定权限添加到应用程序的清单文件:
<uses-permission android:name="android.permission.WAKE_LOCK" />
如果您的应用程序包含使用服务执行某些工作的广播接收器,您可以通过WakefulBroadcastReceiver管理唤醒锁定。这是首选方法。如果您的应用程序不遵循该模式,您可以直接设置唤醒锁定。您正在启动粘性服务。这将确保您的服务在启动时将重新启动由framework调用。但是如果调用stopSelf()然后它将被终止,不再启动。在您的特定情况下,我不确定是谁终止了服务。但您可以尝试的一个选项是获得唤醒锁。如果您获得唤醒锁,它将阻止框架终止它。一旦您的事务结束,您可以释放唤醒锁,让框架自由地终止它。这是不是oach工作了??oncreate在服务上?我应该什么时候释放此唤醒锁?当您完成任务并且不再需要唤醒锁时,您可以释放它。您也可以在服务的onDestroy中执行此操作。它似乎对我有效,非常感谢
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
wakelock.acquire();