简体   繁体   English

如何在Android中检查小部件是否在后台

[英]how to check if widget is in background in android

I am developing torch. 我正在开发火炬。 I have developed widget with a single button. 我已经开发了一个按钮的小部件。 If you click on that button it turns on torch and if you click again it turns off torch. 如果单击该按钮,它将打开手电筒;如果再次单击,则将关闭手电筒。 BUT when torch is ON and user pressed Power button to turn off screen it also turns off the torch. 但是,当割炬打开且用户按下电源按钮以关闭屏幕时,它也会关闭割炬。 So I want to check if device has gone to sleep mode while torch was on, can someone help me ? 因此,我想检查在割炬打开时设备是否已进入睡眠模式,有人可以帮我吗?

here is my code to turn torch on and off in widget 这是我在小部件中打开和关闭手电筒的代码

public void onReceive(Context context, Intent intent) {
    Log.d("torchWidget", "onReceive");
    final String action = intent.getAction();
    if(AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
        final int appWidgetId = intent.getExtras().getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if(appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            this.onDeleted(context, new int[] { appWidgetId });
        }
    } else{

        if(intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
            String msg = "null";
            try{
                msg = intent.getStringExtra("msg");
                msg = "Flash Turned On";
            } catch(NullPointerException e) {
                Log.e("Error", "msg = null");
            }
            if(Constants.isFlashOnWidget){
                Constants.isFlashOnWidget = false;
                Toast.makeText(context, "Flash turned OFF", Toast.LENGTH_SHORT).show();

                 Intent serviceIntent = new Intent(context.getApplicationContext(),
                         BackgroundService.class);

                        context.stopService(serviceIntent);

            } else {   
                Constants.isFlashOnWidget = true;
                 Intent serviceIntent = new Intent(context.getApplicationContext(),
                         BackgroundService.class);

                        context.startService(serviceIntent);

            }

        }
        super.onReceive(context, intent);
    }

PowerManager系统服务检查isScreenOn()方法

您的应用或小部件是否可以保存并在以后使用savedInstanceState()检查其状态,如有关恢复活动的android文档http://developer.android.com/training/basics/activity-lifecycle/recreating.html中所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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