如果您希望设备在显示您的应用程序的活动时保持清醒,您必须在创建活动时设置标志 FLAG_KEEP_SCREEN_ON:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // Unlock the device if locked
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); // Turn screen on if off
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keep screen on
.....
}
在清单中添加权限 WAKE_LOCK:
<uses-permission android:name="android.permission.WAKE_LOCK" />
编辑在看到您的最后一条评论后:是的,您需要一项服务:请注意,设备无论如何都会进入睡眠状态,但如果您向用户明确说明(您必须显示通知)并声明它,您的服务可以继续运行黏:
public class yourservice extends Service
{
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//The intent to launch when the user clicks the expanded notification
/////////////////////////////////////////////////////////////////////
Intent forPendingIntent = new Intent(this, si.test.app.activities.activity.class);
forPendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, forPendingIntent, 0);
Notification notification = new Notification(R.drawable.icon, "testapp", System.currentTimeMillis());
notification.setLatestEventInfo(this, "testApp", "testApp is running", pendIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground (R.string.app_name, notification);
return START_STICKY;
}
...
}