简体   繁体   中英

How can I prevent a background Service in Android from being force stopped?

I need some help for creating a service which can also keep running in background even if an application has being force stopped by user. So how can I do this? Can anybody help me out? Here following I also given my developed code for 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();
    }
}

But by using this code I can't get the service keep alive in background. When I force stop an application, the service also stops. I want to keep the service alive in background.

If by "force-stopped" you literally mean the user pressing "Force Stop" in the Settings page for your app, your app is stopped. Period. There is nothing you can do to prevent this.

Moreover, your app will never run again on this device , until the user does something that manually runs one of your components -- usually, this is by launching one of your activities.

START_STICKY helps on some versions of Android for more "casual" scenarios, such as the user swiping away your app from the recent-tasks list (though reportedly this does not work on Android 4.4, and it's unclear if that is intentional or a bug in the OS).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM