终止时重新启动服务

时间:2014-05-21 14:04:38

标签: android android-intent service

我的应用程序服务连接到服务器并检查新帖子。问题是当应用程序从"最近的应用程序"列表或强制关闭时,它会被终止,否则它可以正常工作。有什么方法可以重新启动服务吗?例如我能听的任何广播?我已经添加了BootCompleteReceiver。

以下代码:

PostCheckService.java

package com.royal.bikers;

import static com.royal.bikers.resources.Constants.KEY_DATA;
import static com.royal.bikers.resources.Constants.KEY_ERROR;
import static com.royal.bikers.resources.Constants.KEY_MSG;
import static com.royal.bikers.resources.Constants.KEY_SIZE;
import static com.royal.bikers.resources.Constants.URL_EVENT;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.royal.bikers.resources.Functions;
import com.royal.bikers.resources.JSONParserForSearch;

public class PostsCheckService extends Service {

    private Timer timer;
    int newsize, diff, oldsize;
    private Functions functions = new Functions();
    NotificationManager mNotifyMgr;

    private TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            Log.i("TASK", "Checking for new posts");
            JSONParserForSearch jParser = new JSONParserForSearch();
            // Getting JSON from URL
            mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            JSONObject json = jParser.getJSONFromUrl(URL_EVENT);
            try {
                if (functions.isConnected(getApplicationContext())) {
                    if (functions.isUserLoggedIn(getApplicationContext())) {
                        Log.i("json log", "JSON RECEIVED");
                        String message = json.getString(KEY_MSG);
                        if (json.getInt(KEY_ERROR) == 0) {
                            JSONArray data = json.getJSONArray(KEY_DATA);
                            newsize = data.length();
                            oldsize = functions.getSharedPrefrences(
                                    getApplicationContext(), KEY_SIZE);
                            if (newsize > oldsize) {
                                diff = newsize - oldsize;
                                Intent toSearch = new Intent(getApplication(),
                                        SearchActivity.class);
                                toSearch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                functions.putSharedPrefrences(
                                        getApplicationContext(), KEY_SIZE,
                                        newsize);
                                if (diff == 1) {

                                    showNotification("One New Event",
                                            "Tap to see new event",
                                            R.drawable.ic_notification,
                                            toSearch);
                                } else {
                                    showNotification(String.valueOf(diff)
                                            + " New Events",
                                            "Tap to see new events",
                                            R.drawable.ic_notification,
                                            toSearch);
                                }
                                Log.i("NEW POST", String.valueOf(diff));
                                oldsize = newsize;
                                functions.putSharedPrefrences(
                                        getApplicationContext(), KEY_SIZE,
                                        newsize);
                            } else if (newsize < oldsize) {
                                oldsize = newsize;
                                Log.i("Size Reduced By",
                                        String.valueOf(oldsize - newsize));
                                functions.putSharedPrefrences(
                                        getApplicationContext(), KEY_SIZE,
                                        newsize);
                            } else {

                                Log.i("NEW POST", "NONE");
                            }
                        } else {
                            Log.e("ERROR", message);
                        }
                    } else {
                        Log.e("ERROR", "Not Logged In");
                        mNotifyMgr.cancelAll();
                        Intent toLogin = new Intent(getApplication(),
                                LoginActivity.class);
                        toLogin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        showNotificationNoSound("Login Required",
                                "Tap to login into Royal Bikers",
                                R.drawable.ic_notification, toLogin);
                    }
                } else {
                    Log.e("ERROR", "Not Connected");

                    mNotifyMgr.cancelAll();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("TASK", "Service creating");

        timer = new Timer("NewPostTimer");
        timer.schedule(updateTask, 1000L, 10 * 1000L);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("TASK", "Service destroying");

        timer.cancel();
        timer = null;
    }

    public void showNotification(String title, String subtitle, int icon,
            Intent resultIntent) {
        Uri soundUri = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pendingResultIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, resultIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification mBuilder = new NotificationCompat.Builder(
                getApplicationContext()).setContentTitle(title)
                .setContentText(subtitle).setSmallIcon(icon)
                .setContentIntent(pendingResultIntent).setSound(soundUri)
                .setAutoCancel(true).build();
        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.cancelAll();
        mNotifyMgr.notify(0, mBuilder);
    }

    public void showNotificationNoSound(String title, String subtitle,
            int icon, Intent resultIntent) {

        PendingIntent pendingResultIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, resultIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification mBuilder = new NotificationCompat.Builder(
                getApplicationContext()).setContentTitle(title)
                .setContentText(subtitle).setSmallIcon(icon)
                .setContentIntent(pendingResultIntent).setAutoCancel(true)
                .build();
        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.cancelAll();
        mNotifyMgr.notify(0, mBuilder);
    }
}

BootCompleteReceiver.java

package com.royal.bikers.resources;

import com.royal.bikers.PostsCheckService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootCompletedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent serviceIntent = new Intent(context, PostsCheckService.class);
        context.startService(serviceIntent);
    }
}

Android Manifest中的服务和接收器

<service
            android:name="com.royal.bikers.PostsCheckService"
            android:exported="false"
            android:process=":remote" >
            <intent-filter>
                <action android:name="com.royal.bikers.PostsCheckService" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.royal.bikers.resources.BootCompletedReceiver"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

我在onStartCommand()声明中使用START_STICKY尝试return,但它没有帮助。但是,如果你可以指导我正确实施onStartCommand(),我会很高兴。

1 个答案:

答案 0 :(得分:1)

在后台每10秒轮询一次新帖子,除非用户明确要求该轮询频率。这将很快耗尽用户的电池。每10分钟分钟的轮询可能比用户想要的更多。

然后,使用Timer进行后台轮询。将AlarmManagerIntentService一起使用,这样您的应用就可以在轮询操作之间关闭。这样做的另一个好处是,即使在其他原因(例如,用户将应用程序从最近任务列表中滑出)终止后,您的应用仍可继续获得控制权。

相关问题