如何使即使被系统杀死也无法移动的服务?

时间:2018-09-28 06:35:45

标签: android service

我正在创建蓝光滤镜应用程序。因此,我想显示所有应用程序的视图。我是通过以下服务做到的,

public class OverlayService extends Service {
    public OverlayService() {}
    View mView;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();

        WindowManager.LayoutParams params;
        if (Build.VERSION.SDK_INT < 26)
            params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, 
                    PixelFormat.TRANSLUCENT);
        else
            params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                    PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        mView = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.overlay, null);
        wm.addView(mView, params);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mView != null) {
            ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
        }

    }
}

工作正常。

  

”如果我从最近的应用中删除应用,它将停止服务,然后自动   几秒钟后启动服务”

     

为什么停止并重新启动服务?如何避免这种情况?

我尝试覆盖 onStartCommand()并使用了START_STICKY 。但是没用。

帮帮我。在此先感谢!

3 个答案:

答案 0 :(得分:1)

首先创建 BroadcastReceiver

public class Restarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.i("Broadcast Listened", "Service tried to stop");
    Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, YourService.class));
    } else {
        context.startService(new Intent(context, YourService.class));
    }
 } 
}

在您的服务中添加以下代码

 @Override
public void onDestroy() {
    super.onDestroy();
    stoptimertask();

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("restartservice");
    broadcastIntent.setClass(this, Restarter.class);
    this.sendBroadcast(broadcastIntent);
}



private Timer timer;
private TimerTask timerTask;
public void startTimer() {
    timer = new Timer();
    timerTask = new TimerTask() {
        public void run() {
            Log.i("Count", "=========  "+ (counter++));
        }
    };
    timer.schedule(timerTask, 1000, 1000); //
}

public void stoptimertask() {
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

在您的MainActivity中添加以下代码

public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private YourService mYourService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mYourService = new YourService();
    mServiceIntent = new Intent(this, mYourService.getClass());
    if (!isMyServiceRunning(mYourService.getClass())) {
        startService(mServiceIntent);
    }
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            Log.i ("Service status", "Running");
            return true;
        }
    }
    Log.i ("Service status", "Not running");
    return false;
}


@Override
protected void onDestroy() {
    stopService(mServiceIntent);
    super.onDestroy();
}   }

在Manifest.XML中

 <receiver
    android:name="Restarter"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="restartservice" />
    </intent-filter>
</receiver>

答案 1 :(得分:0)

尝试一下 在服务类中添加此方法

@Override
public void onTaskRemoved(Intent rootIntent){
    super.onTaskRemoved(rootIntent);
 }

答案 2 :(得分:0)

该服务必须重新启动,因为android不允许它。您可以使用Foreground服务来改善您的应用。