0

Здравствуйте. Подскажите, пожалуйста, в одном проекте есть activity и service, как сделать чтобы когда удаляешь процесс, удалялась только activity, а service оставался?

Вот полный код MainActivity.class

public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {

final String LOG_TAG = "myLogs";
final String serviceName = "ua.intsystems.screenturn.action.startforeground";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout linLayout = new LinearLayout(this);
    linLayout.setOrientation(LinearLayout.VERTICAL);

    LinearLayout.LayoutParams linParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    LinearLayout.LayoutParams viewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    ListView listV = new ListView(this);

    Switch s = new Switch(this);
    s.setLayoutParams(viewParams);
    if (s != null)
        s.setOnCheckedChangeListener(this);
    if(isServiceRunning())
        s.setChecked(true);
    else
        s.setChecked(false);

    /*View view[] = {s};

    AdapterView adapter = new AdapterView(this,
            android.R.layout.simple_list_item_1, view);
    listV.setAdapter(adapter);*/

    linLayout.addView(s);

    setContentView(linLayout, linParams);

}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Intent intent = new Intent(MainActivity.this, ScreenOnService.class);
    intent.setAction(serviceName);

    if(isChecked)
        startService(intent);
    else
        stopService(intent);
}

private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceName.equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
}

И ScreenOnService.class

public class ScreenOnService extends Service implements SensorEventListener {

final String LOG_TAG = "Logs: ";
private SensorManager sm;
private float x;
private float y;
private float z;
private float distance;
private float far;
private float light;
private Sensor mAccelerometer;
private Sensor mProximity;
private Sensor mLight;
private PowerManager pm;
private PowerManager.WakeLock wakeLock;
private KeyguardManager key;
private KeyguardManager.KeyguardLock keyLock;
private boolean continueWhile = true;

public void onCreate() {
    super.onCreate();

    sm = (SensorManager)getSystemService(SENSOR_SERVICE);
    mAccelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mProximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mLight = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
    sm.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    sm.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
    sm.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);

    key = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
    keyLock = key.newKeyguardLock("TAG");

    pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock((PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE), "TAG");

    far = mProximity.getMaximumRange();
    distance=far;

    Log.d(LOG_TAG, "onCreate");
}

public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");
    Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),
            System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, ScreenOnService.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),
            getText(R.string.app_name), pendingIntent);
    startForeground(1, notification);
    /*Notification note = new Notification( 0, null, System.currentTimeMillis() );
    note.flags |= Notification.FLAG_NO_CLEAR;
    startForeground(42, note);*/
    someTask();
    return START_STICKY;
}

public void onDestroy() {
    super.onDestroy();
    continueWhile = false;
    sm.unregisterListener(this);
    Log.d(LOG_TAG, "onDestroy");
}

public IBinder onBind(Intent intent) {
    Log.d(LOG_TAG, "onBind");
    return null;
}

void someTask() {
    new Thread(new Runnable() {
        public void run() {
            while(continueWhile) {
                //Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 10);
                if (!pm.isScreenOn()) {
                    keyLock.reenableKeyguard();
                    if(distance<far && light>= 5) {
                        keyLock.disableKeyguard();
                        wakeLock.acquire();
                        distance=far;
                        /*try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                        wakeLock.release();
                        Log.d(LOG_TAG, "Screen ON");
                    }
                }
            }
        /*
            for (int i = 1; i<=5; i++) {
                Log.d(LOG_TAG, "i = " + i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            //stopSelf();
        }
    }).start();
}

@Override
public void onSensorChanged(SensorEvent event) {
    if(!pm.isScreenOn())
    switch(event.sensor.getType()){
        case Sensor.TYPE_ACCELEROMETER:
            x=event.values[0];
            y=event.values[1];
            z=event.values[2];
        break;
        case Sensor.TYPE_PROXIMITY:
            distance=event.values[0];
            Log.d("Distance: ", Float.toString(distance));
        break;
        case Sensor.TYPE_LIGHT:
            light=event.values[0];
            Log.d("Light: ", Float.toString(light));
        break;
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

}
2
  • 1
    А как убиваете процесс? 15 дек 2014 в 23:04
  • Убиваю с помощью встроеного диспетчера задач, там отображается activity, я его в сторошу сдвигаю и процесс заершается Activity вместе с Service, хотя на самом телефоне есть встроенные приложения у которых сервсы работают отдельно от activity
    – Kl0nLutiy
    16 дек 2014 в 11:25

1 ответ 1

1

Попробуйте добавить соответствующий флаг в intent, стартующий сервис:

Intent intent = new Intent(context, YoursService.class);
//указываем, что сервис не должен зависеть от жизненного цикла активити
intent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(intent);

Обновление

Если я правильно понял то, что гугл выдаёт на этот счёт, то единственный способ не дать умереть сервису при смерти приложения - вывод Notification из сервиса через

int notificationId=10;
startForeground(notificationId, notification);
5
  • Насколько я понял, это вот этот мануал: truiton.com/2014/10/android-foreground-service-example, пробывал не помог
    – Kl0nLutiy
    15 дек 2014 в 22:56
  • Да, оттуда как раз. Обновил ответ
    – ЮрийСПб
    15 дек 2014 в 23:05
  • пробывал не помогает вот код Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, getText(R.string.app_name), getText(R.string.app_name), pendingIntent); startForeground(1, notification);
    – Kl0nLutiy
    15 дек 2014 в 23:39
  • @Kl0nLutiy, да, тут вот спрашивают как процесс убиваете? У меня, насколько я помню, когда я делал, как выше описано, всё работало как надо - активити помирало, а сервис продолжал работать.
    – ЮрийСПб
    16 дек 2014 в 3:12
  • Добавил полный код
    – Kl0nLutiy
    16 дек 2014 в 22:43

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.