当应用程序未运行时,ANDROID中的ScreenReceiver for Screen On / Off

时间:2017-02-26 11:28:07

标签: android broadcastreceiver

我想检测屏幕关闭和开启事件,因为我已经创建了BroadcastReceiver,它只能在应用程序运行时正常工作,当我从任务管理器中删除应用程序时,它不起作用。

的活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try{
        BroadcastReceiver myrcver  = new BootReceiver();
        IntentFilter screenStateFilter = new IntentFilter();
        screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
        screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(myrcver, screenStateFilter);
    }
    catch (Exception e){
        e.fillInStackTrace();
    }
}

Menifest:

<receiver
        android:name=".BootReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="BootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.SCREEN_OFF" />
            <action android:name="android.intent.action.SCREEN_ON" />
        </intent-filter>
    </receiver>

广播接收者:

public class BootReceiver extends BroadcastReceiver {
boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
    try {
        if ("android.intent.action.SCREEN_ON".equals(intent.getAction())) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                screenOff = true;
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                screenOff = false;
            }
            Intent i = new Intent(context, UpdateService.class);
            i.putExtra("screen_state", screenOff);
            context.startService(i);
        }
    }
    catch (Exception e){
        e.fillInStackTrace();
    }
}

}

提前获得帮助。

3 个答案:

答案 0 :(得分:1)

如果您希望它在后台运行,即使应用程序未运行,您也必须创建一个服务。 在服务类中,您必须注册接收者。

public class ScreenOnOffService extends Service {

    private ScreenOnOffReceiver mScreenReceiver;

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

    @Override
    public void onCreate() {
        registerScreenStatusReceiver();
    }

    @Override
    public void onDestroy() {
        unregisterScreenStatusReceiver();
    }

    private void registerScreenStatusReceiver() {
        mScreenReceiver = new ScreenOnOffReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenReceiver, filter);
    }

    private void unregisterScreenStatusReceiver() {
        try {
            if (mScreenReceiver != null) {
                unregisterReceiver(mScreenReceiver);
            }
        } catch (IllegalArgumentException e) {}
    }
}

创建服务类后,不要忘记将您的服务添加到Manifest:

<service android:name="com.myapp.services.ScreenOnOffService" />

然后,要启动该服务,您可以在主要活动中写下:

Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);

对于广播课程:

public class ScreenOnOffReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Log.d("StackOverflow", "Screen Off");

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Log.d("StackOverflow", "Screen On");
        }
    }
}

注意:对我而言screen offscreen on NOT 在清单中工作,但仅限于运行时。

答案 1 :(得分:0)

参加聚会有点晚,但可能会帮助某人。 按照上面@CookieMonster的说明进行操作,进一步在启动服务 ScreenOnOffService 时,这样做

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

,然后在您的 ScreenOnOffService onCreate()方法中粘贴以下代码

if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "your_channel_id";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "Notification Channel Title",
                NotificationManager.IMPORTANCE_DEFAULT);

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();

        startForeground(1, notification);
    }

现在运行您的应用程序。它将按预期工作。

答案 2 :(得分:-1)

只有在清单中添加权限wake.lock时才能在应用程序未运行时运行广播投递接收器