在许多音乐应用中,一般都会附带有锁屏时切换壁纸,解屏时还原的功能以及有开屏时的状态通知栏有歌曲的提示和播放进度等。
现在来说说怎么简单的就实现锁屏切换壁纸的功能。
首先,要先写好广播,用于监听锁屏和开屏等系统广播,如下:
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
private String action = null;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
// 锁屏
SetWallPagerWhenOff();
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
// 解锁
SetWallPagerWhenOn();
}
}
};
其次,在权限配置那加上:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
当然,可以在权限配置文件中写上系统广播,也可以在Activity中动态注册,如下:
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
this.registerReceiver(mybroadcast, filter);
那么,剩下的问题就在于如何获取当前的系统壁纸和替换,还原,如下:
wm = (WallpaperManager) this
.getSystemService(Context.WALLPAPER_SERVICE);//获取壁纸管理器
image2 = (ImageView) this.findViewById(R.id.img2);
drawable = wm.getDrawable();//获取壁纸
image2.setImageDrawable(drawable);
startScreenBroadCasetReceiver();//动态注册广播
public void SetWallPagerWhenOff() {壁纸替换
try {
wm.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.a));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SetWallPagerWhenOn(){壁纸还原
try {
wm.setBitmap(drawable2Bitmap(drawable));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
那么,简单的壁纸随锁屏开屏的切换已经完成。