Android后台服务和唤醒锁

时间:2015-08-19 02:27:45

标签: android service background

我有android后台服务来连接我的RabbitMQ服务器。我的后台服务收听传入的rabbitmq消息。一切都运行良好,但问题出现在屏幕熄灭时。手机屏幕关闭时我的android客户端断开连接。我应该怎么做才能始终与我的android rabbitmq客户端和rabbitmq服务器连接?

我的代码如下:

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

}

1 个答案:

答案 0 :(得分:0)

如果您的应用程序包含使用服务执行某些工作的广播接收器,则可以通过WakefulBroadcastReceiver管理唤醒锁。这是首选方法。如果您的应用程序不遵循这种模式,则可以直接设置唤醒锁。