Android服务器联系服务保持活力

时间:2012-05-04 14:28:20

标签: android service wakelock

所以我为我正在处理的应用程序提供服务。此服务每隔20秒与我的服务器联系,以查看是否有更新并提供通知(如果有)。我在这里遇到了一些问题。

1)我的服务在大约30分钟后就会死亡。看起来android只是杀了它。我怎么能一直保持活着?

2)正如你在我的代码中看到的那样,我的唤醒锁是很奇怪的。我需要在睡眠期间保持活着以检查通知,但是如果我在等待20秒后获得唤醒锁,则它不起作用。所以现在它发布然后在计时器之前重新获得唤醒锁。这不适合电池等。谁知道更好的方法呢?

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 个答案:

答案 0 :(得分:1)

您正在进行的操作称为轮询,但您需要使用C2DM执行推送通知。您可以在Google IO 2010观看此视频。您可以获取C2DM here的示例代码。