如何防止Android中的后台服务被强制停止?

时间:2014-03-22 13:14:22

标签: android service

我需要一些帮助来创建一个服务,即使应用程序被用户强制停止,该服务也可以继续在后台运行。那我该怎么做呢?有人可以帮帮我吗? 下面我还给出了我开发的服务代码。

public class LogManager_Service extends Service {

    DatabaseHandler db;
    Intent intent;
    Context context = this;
// calls
    String phonenumber;
    String callId = "", number = "", call_type = "", call_datetime = "";
    String dir = "";
// sms-mms
    String direction = "";
    String address = "";
    String Type, cnt_type;
    boolean isIncoming = false;
    int smsID, outsmsId;
    Long timestamp, sms_timestamp_in, sms_timestamp_out;
    long aftertime;
    Cursor cu;
    private static Timer timer = new Timer();

    static boolean ring = false;
    static boolean callReceived = false;

    SharedPreferences my_date_Prefs;

    @Override
    public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
// TODO Auto-generated method stub
        super.onCreate();

        my_date_Prefs = PreferenceManager.getDefaultSharedPreferences(this);

        db = new DatabaseHandler(context);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
        super.onStartCommand(intent, flags, startId);

        aftertime = my_date_Prefs.getLong("ApplicationStrat_time", 0);
        timer.scheduleAtFixedRate(new mainTask(), 0, 1000);
        System.out.println("<==========Service Start==========>");
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
// TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onRebind(Intent intent) {
// TODO Auto-generated method stub
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
        return super.onUnbind(intent);
    }



    private class mainTask extends TimerTask {
        public void run() {
            toastHandler.sendEmptyMessage(0);
        }
    }

    private final Handler toastHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Uri myMessage1 = Uri.parse("content://sms/sent");
            ContentResolver cr1 = getContentResolver();
            Cursor c1 = cr1.query(myMessage1, new String[] {"_id", "address", "date", "body","read" }, null, null, null);
            if (c1 != null) {

                try {
                    int count = c1.getCount();
                    if (count > 0) {
                        c1.moveToFirst();
                        number = c1.getString(1);
                        Type = "OS";
                        String sms_date_out = c1.getString(2);
                        String substr = sms_date_out.substring(sms_date_out.length() - 3);
                        outsmsId = Integer.parseInt(substr);
                        String sms_body = c1.getString(3);
                        System.out.println("SMS Date Normal for SENT ======>"+ sms_date_out);
                        sms_timestamp_out = Long.parseLong(sms_date_out);
                        if (sms_timestamp_out >= aftertime ) {
                            addSMS(outsmsId, number, Type,  sms_timestamp_out,sms_body, "");
                        }

                    }

                } finally {
                    c1.close();
                }
            }

        }
    };  

    private void addSMS(int smsID, String number, String type,Long sms_timestamp_in, String sms_body, String call_duration) {
// TODO Auto-generated method stub
        System.out.println("smsID ====>" + smsID);
        System.out.println("number ====>" + number);
        System.out.println("type ====>" + type);
        System.out.println("sms_timestamp_in ====>" + sms_timestamp_in);
        System.out.println("sms_body ====>" + sms_body);
        db.addSMSDetails(smsID, number, type, sms_timestamp_in, sms_body,call_duration);
        db.close();
    }
}

但是通过使用此代码,我无法在后台保持服务。当我强制停止应用程序时,该服务也会停止。我想让服务在后台保持活力。

2 个答案:

答案 0 :(得分:1)

如果通过“强制停止”,您的字面意思是用户在您的应用的“设置”页面中按“强制停止”,您的应用就会停止。期。你无能为力阻止这一点。

此外,您的应用将永远不会在此设备上再次运行,直到用户执行手动运行您的某个组件的操作 - 通常是启动您的某项活动。

START_STICKY可帮助某些版本的Android获得更多“随意”方案,例如用户将您的应用从最近任务列表中删除(虽然据说这在Android 4.4上无效,但目前还不清楚这是故意的或操作系统中的错误。)

答案 1 :(得分:1)

在onStartCommand()上设置“return START_STICKY”,而不是返回START_NOT_STICKY。