1

我想实现一个最小的屏幕活动记录器应用程序。因此,应用程序应该在后台运行(没有用户交互),它会记录屏幕的开启和关闭活动。我已经启动了这些代码,但似乎我需要注册我的ScreenBroadcastReceiver broadcastreceiver. 如果我在主要活动中使用以下代码执行此操作,则它可以工作。但是,我不想在 main 中注册它,因为用户无法每次都启动该活动。那么,我应该在哪里注册BroadcastReceiver以便应用程序在没有用户交互的情况下工作?

oncreate在主要活动中

    //I need to find another place to put these code, Where ???
    //IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    //filter.addAction(Intent.ACTION_SCREEN_OFF);
    //BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
    //registerReceiver(screenOnReceiver, filter);

这是 ScreenBroadcastReceiver,它会在屏幕开启时触发。

public class ScreenBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
     if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        Log.w("OnReceive", "SCREEN IS ON");
        }
    }

}

这是在后台运行程序的 BootReceiver。

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, ScreenListenerService.class);
        context.startService(service);

            //IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            //filter.addAction(Intent.ACTION_SCREEN_OFF);
        //BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
        //context.registerReceiver(screenOnReceiver, filter);
    }

}

这是清单:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 <service android:name=".ScreenListenerService"></service>

 <receiver android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

更新:

我添加了一项服务,但它不起作用。我忘了添加什么吗?或者是什么 ?

public class ScreenListenerService extends Service {

    public void OnCreate(){

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
        registerReceiver(screenOnReceiver, filter);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}
4

1 回答 1

1

服务用于您的目的,并按照您在活动中所做的那样做。

于 2013-04-28T03:24:37.677 回答