Android-Service实现手机壁纸自动更换
本文实例为大家分享了Android Service实现自动更换手机壁纸的具体代码,供大家参考,具体内容如下
创新互联公司是一家专注于网站设计、网站建设与策划设计,吴江网站建设哪家好?创新互联公司做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:吴江等地区。吴江做网站价格咨询:18980820575
先看下效果:
使用界面:
划重点,使用service前别忘了给相应的service添加服务
具体实现:
首先定义ChangeService类,继承Service访问系统实现壁纸切换
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来实现壁纸更换:
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); } }); } }
布局设计:
<?xml version="1.0" encoding="utf-8"?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
分享标题:Android-Service实现手机壁纸自动更换
转载来于:http://myzitong.com/article/jdopij.html