我为adnroid设计了一个锁屏。当用户按下电源按钮解锁时,我正在尝试使用广播接收器来启动锁屏活动。
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.w("BAM", "Screen went on");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.w("BAM","Screen went off");
}
}
}
android manifest:`
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyLockScreenActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="MyAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>
<activity android:name=".LockScreen"></activity>
</application>
`
private ActionBar actionBar;
private ViewPager viewer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lockscreen);
actionBar = getSupportActionBar();
actionBar.hide();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new Receiver();
registerReceiver(mReceiver, filter);
viewer = (ViewPager) findViewById(R.id.viewr);
viewer.setAdapter(new MyAdapter(getSupportFragmentManager()));
}
但是当用户按下电源按钮时1-3秒后锁屏活动开始。 当用户先按下电源按钮屏幕关闭时启动活动是否合适?我怎么能这样做?
谢谢你的建议。 (抱歉我的英语不好!)
答案 0 :(得分:4)
首先,与其他广泛的意图不同,对于Intent.ACTION_SCREEN_OFF和Intent.ACTION_SCREEN_ON,您不能在Android Manifest中声明它们!我不确定为什么,但它们必须在你的JAVA代码中的IntentFilter中注册
使用:
再次修改
public class YourActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourLayout);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
public class ScreenReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.w("BAM", "Screen went on");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.w("BAM","Screen went off");
}
}
}
}
经过测试,工作过!