Служба контактов с Android-сервером продолжает работать

Так что у меня есть сервис для приложения, над которым я работаю. Эта служба связывается с моим сервером каждые 20 секунд, чтобы узнать, есть ли обновление, и отправляет уведомление, если оно есть. Я сталкиваюсь с несколькими проблемами здесь.

1) Мой сервис обычно умирает примерно через 30 минут. похоже, андроид просто убивает его. как я могу сохранить это все время?

2) как вы можете видеть в моем коде, мой wakelock странный. Мне нужно поддерживать это во время сна, чтобы проверить уведомления, но если я получаю wakelock после ожидания 20 секунд, это не работает. так что прямо сейчас он освобождает, а затем повторно получает Wakelock до таймера. что не хорошо для батареи и тому подобное. Кто-нибудь знает лучший способ сделать это?

import java.io.IOException;
import java.net.UnknownHostException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

public class UpdateService extends Service {
    private boolean isRunning = true;
    String username, pass, outpt;
    String ns = Context.NOTIFICATION_SERVICE;

    int Notify_ID = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        username = intent.getStringExtra("username");
        pass = intent.getStringExtra("pass");

        isRunning = true;
            Thread contact = new Thread(new Contact());
            contact.start();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // Stop the Background thread
        isRunning = false;

    }

    private class Contact implements Runnable {

        public void run() {
            while (isRunning) {

            PowerManager mgr = (PowerManager) UpdateService.this
                    .getSystemService(Context.POWER_SERVICE);
            WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    "MyWakeLock");
            wakeLock.acquire();
            try {
                Thread.currentThread().sleep(20000);
                ServerContact server = new ServerContact("stuff i send to the server");
                outpt = server.connect();
                if (!outpt.equals("false")) {
                    handler.sendEmptyMessage(0);
                }

            } catch (UnknownHostException e) {
                System.err.println("cannot connect to host.");
            } catch (IOException e) {
                System.err.println("Server Contact ERROR!! ");
            } catch (InterruptedException e) {
                System.err.println("thread sleep interrupt ");
            }
            wakeLock.release();
            }

        }

        public Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0) {
                    for (String item : outpt.split("\\s+")) {
                        Notify_ID++;
                        notifySys(item, Notify_ID);
                    }
                }
            }
        };
    }

    public void notifySys(String data, int id) {
        // id/name/location
        try {
            String[] content = data.split("/");
            int icon = R.drawable.wcicon;
            CharSequence tickerText = "Word Circle";
            long when = System.currentTimeMillis();

            Notification notification = new Notification(icon, tickerText, when);

            Context context = getApplicationContext();
            CharSequence contentTitle = content[2];
            CharSequence contentText = "It is your turn!";
            Intent go = new Intent(UpdateService.this, SomeClass.class);


            PendingIntent contentIntent = PendingIntent.getActivity(
                    UpdateService.this, 0, go, 0);

            notification.setLatestEventInfo(context, contentTitle, contentText,
                    contentIntent);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
            notification.defaults = Notification.DEFAULT_ALL;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(Notify_ID, notification);

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}

1 ответ

Решение

То, что вы делаете, известно как опрос, но вам нужно сделать Push-уведомление с использованием C2DM. Вы можете посмотреть это видео в Google IO 2010. Пример кода для C2DM можно найти здесь.

Другие вопросы по тегам