android背景图片更换——经典例子
手机背景和电脑一样,也必要我们去更换图片。如果你觉得太单调,可以把它改成自己喜欢的图片,下面我们来看一下背景的图片更换程序,是如何编写的。我们先看一下图先
package com.smart.image; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Main extends Activity implements OnClickListener{ private Button startImage; private Button stopImage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startImage=(Button)findViewById(R.id.statrImage); stopImage=(Button)findViewById(R.id.stopImage); stopImage.setEnabled(false);//刚开始显示为false startImage.setOnClickListener(this);//绑定器 stopImage.setOnClickListener(this); } @Override public void onClick(View v) { //获得服务 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); //启动 PendingIntent pendingIntent = PendingIntent.getService(this, 0, new Intent(this, ChangeBackground.class), 0); switch (v.getId()) { //按钮事件 开始更换背景图片 case R.id.statrImage: alarmManager.setRepeating(AlarmManager.RTC, 0, 5000, pendingIntent); startImage.setEnabled(false); stopImage.setEnabled(true); break; //按钮事件停止图片更换 case R.id.stopImage: alarmManager.cancel(pendingIntent); startImage.setEnabled(true); stopImage.setEnabled(false); break; } } }
方法实现类
package com.smart.image; import java.io.InputStream; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ChangeBackground extends Service { private static final String TAG="ChangeBackground"; private static int index = 0;//数组元素从0开始 //图片数组 private int[] resIds = new int[] { R.raw.one, R.raw.two, R.raw.three, R.raw.four, R.raw.five, R.raw.six, R.raw.seven}; @Override public void onStart(Intent intent, int startId) { if(index==7) index=0; InputStream inputStream=getResources().openRawResource(resIds[index++]);//得到资源图片的元素 try { setWallpaper(inputStream);//显示图片 } catch (Exception e) { Log.i(TAG, e.toString());//查看错误信息 } super.onStart(intent, startId); } //创建 @Override public void onCreate() { super.onCreate(); } @Override public IBinder onBind(Intent arg0) { return null; } }