简体   繁体   中英

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中所述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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