Android桌面三:手机壁纸
手机壁纸
手机壁纸分为静态壁纸和动态壁纸,设置方式也不同
一:静态壁纸
Android允许使用WallpaperManager来改变手机壁纸,提供了如下方法进行设置:
-
setBitmap(Bitmap bitmap):将壁纸设置为bitmap所代表的位图
-
setBitmap(Bitmap bitmap):将壁纸设置为bitmap所代表的位图
-
setResoutce(int resid):将壁纸设置为resid所代表的图片
-
setStream(InputStream data):将壁纸设置为data数据所代表的图片
1,设置壁纸:
第一种方式:打开系统的壁纸设置程序进行设置
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper, getString(R.string.choose_wallpaper));
startActivity(chooser);
第二种方式:直接为壁纸设置图片
1,设置静态壁纸
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
wallpaperManager.setResource(R.drawable.bbb);
} catch (IOException e) {
e.printStackTrace();
}
2,清除壁纸:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
wallpaperManager.clear();
} catch (IOException e) {
e.printStackTrace();
}
3,设置权限
设置壁纸需添加壁纸的权限:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
清除壁纸需添加设置权限:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
二:动态壁纸
使用步骤
- 首先创建一个壁纸Service(LiveWallpaperService),继承WallpaperService
- 在LiveWallpaperService中创建一个引擎(LiveWallpaperEngine),继承LiveWallpaperService.Engine
- 在LiveWallpaperService的onCreateEngine方法中,返回LiveWallpaperEngine的实例
- 在AndroidManifest添加Service
实例:
layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:loadview="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/setStaticBack"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择静态壁纸" />
<Button
android:id="@+id/setVideoBack"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择动态壁纸" />
<CheckBox
android:layout_width="wrap_content"
android:id="@+id/id_cb_voice"
android:text="是否为静音"
android:layout_height="wrap_content" />
</LinearLayout>
xml/livewallpaper.xml
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
android:thumbnail="@mipmap/ic_launcher" />
app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
-----------------------------------------------------------------------------------------
<!-- 配置实时壁纸Service -->
<service
android:name=".VideoLiveWallpaper"
android:label="@string/app_name"
android:permission="android.permission.BIND_WALLPAPER"
android:process=":wallpaper">
<!-- 为实时壁纸配置intent-filter -->
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<!-- 为实时壁纸配置meta-data -->
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/livewallpaper" />
</service>
com/example/administrator/MainActivity.java
package com.example.administrator;
import android.Manifest;
import android.app.WallpaperManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import com.example.administrator.Permission.PermissionManager;
public class MainActivity extends AppCompatActivity implements PermissionManager.PermissionsResultListener {
private CheckBox mCbVoice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PermissionManager.requestPermission(this, "设置动态壁纸所需权限", 2, this, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_WALLPAPER, Manifest.permission.WRITE_SETTINGS);
mCbVoice = findViewById(R.id.id_cb_voice);
mCbVoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 静音
VideoLiveWallpaper.voiceSilence(getApplicationContext());
} else {
VideoLiveWallpaper.voiceNormal(getApplicationContext());
}
}
});
findViewById(R.id.setStaticBack).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper, getString(R.string.choose_wallpaper));
startActivity(chooser);
//或
//设置静态壁纸
// WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
// try {
// wallpaperManager.setResource(R.drawable.bbb);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
});
findViewById(R.id.setVideoBack).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
settingVedio();
}
});
}
private void settingVedio() {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("video/*");
}
startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
//从相册选取视频
Uri dataVideo = data.getData();
SharedPreferences sp = getSharedPreferences("info",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("uri", dataVideo.toString());
Log.i("####", "dataVideo.toString() = " + dataVideo.toString());
editor.commit();
VideoLiveWallpaper.setToWallPaper(MainActivity.this);
}
}
@Override
public void onPermissionGranted(int requestCode) {
}
@Override
public void onPermissionDenied(int requestCode) {
}
}
com/example/administrator/VideoLiveWallpaper.java
package com.example.administrator;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import java.io.IOException;
/**
* thx for https://github.com/songixan/Wallpaper
*/
public class VideoLiveWallpaper extends WallpaperService {
@Override
public Engine onCreateEngine() {
return new VideoEngine();
}
public static final String VIDEO_PARAMS_CONTROL_ACTION = "com.zhy.livewallpaper";
public static final String KEY_ACTION = "action";
public static final int ACTION_VOICE_SILENCE = 110;
public static final int ACTION_VOICE_NORMAL = 111;
public static final String TAG = "VideoLiveWallpaperVideoLiveWallpaper";
public static void voiceSilence(Context context) {
Intent intent = new Intent(VideoLiveWallpaper.VIDEO_PARAMS_CONTROL_ACTION);
intent.putExtra(VideoLiveWallpaper.KEY_ACTION, VideoLiveWallpaper.ACTION_VOICE_SILENCE);
context.sendBroadcast(intent);
}
public static void voiceNormal(Context context) {
Intent intent = new Intent(VideoLiveWallpaper.VIDEO_PARAMS_CONTROL_ACTION);
intent.putExtra(VideoLiveWallpaper.KEY_ACTION, VideoLiveWallpaper.ACTION_VOICE_NORMAL);
context.sendBroadcast(intent);
}
public static void setToWallPaper(Context context) {
final Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, VideoLiveWallpaper.class));
context.startActivity(intent);
}
class VideoEngine extends Engine {
private MediaPlayer mMediaPlayer;
private BroadcastReceiver mVideoParamsControlReceiver;
@SuppressLint("LongLogTag")
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
Log.i(TAG, "VideoEngine#onCreate");
IntentFilter intentFilter = new IntentFilter(VIDEO_PARAMS_CONTROL_ACTION);
registerReceiver(mVideoParamsControlReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
int action = intent.getIntExtra(KEY_ACTION, -1);
switch (action) {
case ACTION_VOICE_NORMAL:
mMediaPlayer.setVolume(1.0f, 1.0f);
break;
case ACTION_VOICE_SILENCE:
mMediaPlayer.setVolume(0, 0);
break;
default:
}
}
}, intentFilter);
}
@SuppressLint("LongLogTag")
@Override
public void onDestroy() {
Log.i(TAG, "VideoEngine#onDestroy");
unregisterReceiver(mVideoParamsControlReceiver);
super.onDestroy();
}
@SuppressLint("LongLogTag")
@Override
public void onVisibilityChanged(boolean visible) {
Log.i(TAG, "VideoEngine#onVisibilityChanged visible = " + visible);
if (visible) {
mMediaPlayer.start();
} else {
mMediaPlayer.pause();
}
}
@SuppressLint("LongLogTag")
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "VideoEngine#onSurfaceCreated ");
super.onSurfaceCreated(holder);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setSurface(holder.getSurface());
try {
//从系统视频中选择
SharedPreferences sp = getSharedPreferences("info", 0);
Uri videoUri = Uri.parse(sp.getString("uri", null));
Log.i("####", "videoUri = " + videoUri);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(getApplicationContext(), videoUri, null);
//从assert中选择
// AssetManager assetMg = getApplicationContext().getAssets();
// AssetFileDescriptor fileDescriptor = assetMg.openFd("test1.mp4");
// mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
// fileDescriptor.getStartOffset(), fileDescriptor.getLength());
mMediaPlayer.setLooping(true);
mMediaPlayer.setVolume(0, 0);
mMediaPlayer.prepare();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mMediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("LongLogTag")
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i(TAG, "VideoEngine#onSurfaceChanged ");
super.onSurfaceChanged(holder, format, width, height);
}
@SuppressLint("LongLogTag")
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "VideoEngine#onSurfaceDestroyed ");
super.onSurfaceDestroyed(holder);
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}