带有DreamService的屏幕保护程序



我正在尝试制作一个简单的屏幕保护程序,它使用DreamService显示图片,但我得到了一个简单的颜色屏幕保护程序。

有我的代码:

安卓清单.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alex.testdreamservice">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<service
android:name=".ScreenSaver"
android:exported="true"
android:label="Picture ScreenSaver">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.service.dreams.DreamService" />
</intent-filter>
</service>
</application>
</manifest>

屏幕保护程序.java

public class ScreenSaver extends DreamService {
@Override
public void onDreamingStarted() {
super.onDreamingStarted();
setFullscreen(true);
setScreenBright(false);
setContentView(R.layout.screensaver_layout);
findViewById(R.id.image_view).setBackground(getDrawableFromAsset("picture.jpeg"));
}
private Drawable getDrawableFromAsset(String url) {
try {
return Drawable.createFromStream(getApplicationContext().getAssets().open(url), null);
} catch (IOException | IllegalArgumentException e) {
e.printStackTrace();
}
return null;
}
}

screensaver_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:textColor="#000000"
android:text="Hello World !"
android:layout_centerInParent="true"/>
</RelativeLayout>

如果有人发现错误,请告诉我。 谢谢!

使用android:permission="android.permission.BIND_DREAM_SERVICE"

<service
android:name=".ScreenSaver"
android:exported="true"
android:label="Picture ScreenSaver"
android:permission="android.permission.BIND_DREAM_SERVICE">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.service.dreams.DreamService" />
</intent-filter>
</service>