锁屏后service不被杀掉

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

public class OnePxActivity extends Activity {

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

        Window window = getWindow();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        WindowManager.LayoutParams params = window.getAttributes();
        params.x = 0;
        params.y = 0;
        params.width = 1;
        params.height = 1;
        window.setAttributes(params);

        registerReceiver(receiver, new IntentFilter("FinishActivity"));
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

	protected BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
            OnePxActivity.this.finish();
		}
    };
}

service.java

BroadcastReceiver myBroadcast = new BroadcastReceiver() {

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(Intent.ACTION_SCREEN_OFF)) {
			Log.i("trans", "screen off");
			Intent activity = new Intent(context, OnePxActivity.class);
			activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(activity);
		} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
			Log.i("trans", "screen on");
			Intent broadcast = new Intent("FinishActivity");
			context.sendBroadcast(broadcast);
		}
	}
};

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
	super.onStartCommand(intent, flags, startId);
	IntentFilter screenStatus = new IntentFilter();
	screenStatus.addAction(Intent.ACTION_SCREEN_OFF);
	screenStatus.addAction(Intent.ACTION_SCREEN_ON);
	registerReceiver(myBroadcast, screenStatus);

	return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(myBroadcast);
}



你可能感兴趣的:(锁屏后service不被杀掉)