Android后台服务和唤醒锁 [英] Android background service and wake lock

查看:72
本文介绍了Android后台服务和唤醒锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有android后台服务与我的RabbitMQ服务器连接.我的后台服务监听传入的Rabbitmq消息.一切工作正常,但问题在屏幕关闭时出现.手机屏幕熄灭时,我的android客户端断开连接.我该怎么做才能始终与我的android Rabbitmq客户端和Rabbitmq服务器连接?

I have android background service to connect with my RabbitMQ server. My background service listen incoming rabbitmq message. Everything is working well but the problem is appear while screen goes off. My android client disconnect when phone screen goes off. What should I do to always connected with my android rabbitmq client and rabbitmq server ?

我的代码如下:

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

}

推荐答案

您需要一个唤醒锁,以在屏幕关闭时保持手机运行.唤醒锁使您的应用程序可以控制主机设备的电源状态.

You need a Wake Lock to keep the phone running when screen is off. Wake locks allow your application to control the power state of the host device.

将WAKE_LOCK权限添加到应用程序的清单文件中:

Add the WAKE_LOCK permission to your application's manifest file:

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

然后在 onCreate()中添加以下内容:

Then add the following in onCreate():

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);  
wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
wakelock.acquire();

这篇关于Android后台服务和唤醒锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆