先看下效果:
使用界面:
划重点,使用service前别忘了给相应的service添加服务
代码语言:javascript复制<service android:name=".ChangeService"></service>
具体实现: 首先定义ChangeService类,继承Service访问系统实现壁纸切换
代码语言:javascript复制public class ChangeService extends Service {
int[] wallpapers = new int[]{
R.drawable.a2, R.drawable.a3, R.drawable.a4
};
WallpaperManager wallpaperManager;
int current = 0;
@Override
public void onCreate() {
super.onCreate();
wallpaperManager = WallpaperManager.getInstance(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (current >= 3) {
current = 0;
} try {
wallpaperManager.setResource(wallpapers[current ]);
} catch (IOException e) {
e.printStackTrace();
} return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
这里我们用闹钟访问pendingIntent来实现壁纸更换:
代码语言:javascript复制public class MainActivity extends Activity {
private Button mStart;
private Button mStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStart = (Button) findViewById(R.id.start);
mStop = (Button) findViewById(R.id.stop);
final Intent intent = new Intent(MainActivity.this, ChangeService.class);
final PendingIntent pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
mStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 2000, pi);
mStart.setEnabled(false); mStop.setEnabled(true);
Toast.makeText(MainActivity.this, "壁纸定时更换启动成功啦", Toast.LENGTH_SHORT).show();
}
});
mStop.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
mStart.setEnabled(true);
mStop.setEnabled(false);
AlarmManager alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
alarmManager.cancel(pi);
}
});
}
}
布局设计:
代码语言:javascript复制<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="@ id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Start"
android:textSize="25dp"
android:textColor="#ffffffff"/>
<Button
android:id="@ id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="Stop"
android:textSize="25dp"
android:textColor="#ffffffff"/>
</LinearLayout>
</RelativeLayout>