设置自动更换主界面背景

Android 专栏收录该内容
265 篇文章 3 订阅

     最近做毕业设计,做一个个人备忘录,想实现这样一个功能:就是可以在设置界面有一个选项,点击自动更换主界面背景,回到主界面,每过10秒更换界面,如果再点击就是关闭自动更换主界面背景。

    设置界面关键代码:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory>
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="@string/auto_huanfu_pifu_key"
            android:summaryOff="@string/auto_update_switch_summary_off"
            android:summaryOn="@string/auto_update_switch_summary_on"
            android:title="@string/auto_huanfu_switch_title" >
        </CheckBoxPreference>
    </PreferenceCategory>

</PreferenceScreen>

      String.xml中相关代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 设置自动更换皮肤 -->
    <string name="auto_huanfu_setting">自动更换皮肤设置</string>
    <string name="auto_huanfu_switch_title">自动更换皮肤</string>
    <string name="auto_huanfu_pifu_key">auto_huanfu_pifu_key</string>
    <string name="auto_huanfu_switch_summary_on">开启自动更换皮肤</string>
    <string name="auto_huanfu_switch_summary_off">关闭自动更换皮肤</string>

</resources>

     接下来就是在设置程序setting.java中找到自动更换界面的按钮,代码如下:

/*
 * 设置界面
 */
package com.note;

import java.io.File;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.view.KeyEvent;
import android.widget.Toast;

//继承PreferenceActivity,并实现OnPreferenceChangeListener和OnPreferenceClickListener监听接口
public class Settings extends PreferenceActivity implements
		OnPreferenceClickListener, OnPreferenceChangeListener {
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	Boolean bo;
	// 定义相关变量
	String huanfu_key;
	CheckBoxPreference huanfuswitch;
	@SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 从xml文件中添加Preference项
		addPreferencesFromResource(R.xml.preferencesii);
		editor = preferences.edit();
                bo = true;


		// 设置自动换肤
		huanfu_key = getResources().getString(R.string.auto_huanfu_pifu_key);
		huanfuswitch = (CheckBoxPreference) findPreference(huanfu_key);
		huanfuswitch.setOnPreferenceClickListener(this);
		huanfuswitch.setOnPreferenceChangeListener(this);

	}

	public boolean onPreferenceClick(Preference preference) {
		
		return true;
	}

	public boolean onPreferenceChange(Preference preference, Object newValue) {
		// 判断是哪个Preference改变了
		if (preference.getKey().equals(updateSwitchKey)) {
			System.out.println("checkbox preference 值改变了");
		} else if (preference.getKey().equals(updateFrequencyKey)) {
			String tixing = (String) newValue;// 重复方式变量
			int num = Integer.parseInt(tixing);
			System.out.println(num + "的值");
			// 重复方式用户选择了定点
			if (num == 1) {
				System.out.println("用户选择了定点的重复方式");
			}
			// 重复提醒方式用户选择了每天
			if (num == 2) {
				System.out.println("用户选择了每天的重复方式");
			}
			// 重复方式用户选择了每周
			else if (num == 3) {
				System.out.println("用户选择了每周的重复方式");
			}
			// 重复提醒方式用户选择了每月
			else if (num == 4) {
				System.out.println("用户选择了每月的重复方式");
			}
			// 重复方式用户选择了单双周
			else if (num == 5) {
				System.out.println("用户选择了单双周的重复方式");
			}
			// 重复方式用户选择了定制
			else if (num == 6) {

				System.out.println("用户选择了定制的重复方式");
			}
			System.out.println(num + "获取用户点击的值");
			System.out.println("list preference 值改变了");
		} else if (preference.getKey().equals(alerttype_key)) {
			String tixing1 = (String) newValue;// 最新的提醒方式变量
			int num1 = Integer.parseInt(tixing1);// 转化成数字类型

			// 用SharedPreferences保存这个提醒方式变量,以使得在Alarm.java能够获取到该变量
			editor.putInt("num1", num1);
			editor.commit();

			// 根据用户选择的提醒方式,更新数据库note相应字段跳转到Alarm.java页面以设置提醒方式
			SqliteDBConnect sd = new SqliteDBConnect(Settings.this);
			SQLiteDatabase sdb = sd.getReadableDatabase();// 取得SQLiteDatabase数据库实例
			// sdb.execSQL("create table note(noteId Integer primary key,noteName varchar(20),noteTime varchar(20),noteContent varchar(400),noteType Integer)");
			ContentValues values = new ContentValues();
			values.put("noteType", num1);
			sdb.update("note", values, null, null);
			// 提醒方式用户选择了定点
			if (num1 == 1) {
				System.out.println("用户选择了振动的提醒方式");
			} else if (num1 == 2) {
				System.out.println("用户选择了铃声的提醒方式");
			} else if (num1 == 3) {
				System.out.println("用户选择了振动和铃声的提醒方式");
			}
			// c1.close();
			sdb.close();

			System.out.println("list preference 值改变了");
		} else if (preference.getKey().equals(huanfu_key)) {
			bo = (Boolean) newValue;
			System.out.println("测试自动更换皮肤会得到的新的值" + bo);
		} else {
			// 如果返回false表示不允许被改变
			return false;
		}
		// 返回true表示允许改变
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) { //
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			//preferences = getSharedPreferences("bo", MODE_WORLD_WRITEABLE);
		    //bo=preferences.getBoolean("bo", true);
			Intent intent = getIntent();
			Bundle bundle = new Bundle();
			bundle.putBoolean("bo", bo);
			System.out.println("得到用户设置的皮肤变量"+bo);
			intent.putExtras(bundle);
			intent.setClass(Settings.this,MainShow.class);
			setResult(11, intent);
			finish();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
    上述代码主要获得用户选择的boolean,如果是true则启动自动更换界面,把这个值传给主界面MainShow.java里,接下来在主界面就要获得这个值,并启动定时器每隔10秒更换界面,如果是禁止自动更换界面,就停止定时器,代码如下:

 

/*
 * 用户启动该软件的主界面,显示从数据库查找的记录,可以点击首页或者末页,也可以点击前后页。
 * 
 * 
 */
package com.note;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.note.Settings;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class MainShow extends Activity {
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> descs = new ArrayList<String>();
	ArrayList<String> fileNames = new ArrayList<String>();
	// 声明通知管理器
	private NotificationManager notificationManager = null;
	private Intent intent = null;
	private PendingIntent pendingIntent = null;
	// 声明Notification对象
	private Notification notification = null;

	boolean isExit; // 判断用户是否要按两次返回键进行退出
	private ListView lv;// 列表view
	private SqliteDBConnect sd;// SqliteDBConnect是一个用来操作SQLiteDatabase辅助类
	private static int page_size = 7;// 一页只能显示7个记录
	private static int page_no = 1, page_count = 0, count = 0;// 标记首页或者末页的变量、默认显示一行记录、总共有几页记录、最大记录数
	private Button btnshezhi, btnChangeSkin, btnAdd, btnFirst, btnEnd,
			btnyaoyiyao, btnGuang; // 分别指添加记事按钮、首页按钮、末页按钮
	private ImageButton btnNext, btnPre;// 分别指上一页图片按钮、下一页图片按钮
	private SimpleAdapter sa;
	private ProgressBar m_ProgressBar;
	private ActivityManager1 am;// 自定义Activity管理工具类
	private RelativeLayout relalayout;
	PendingIntent pi;// 可以理解为延迟执行的intent,PendingIntent是对Intent一个包装
	AlarmManager alm;
	// 系统主界面进行自动换肤的四张图片
	int[] huanfuid = new int[] { R.drawable.huanfu1, R.drawable.huanfu2,
			R.drawable.huanfu3, R.drawable.huanfu4 };
	int currentpifu = 0;// 使图片能循环显示
	Boolean huanfu;//标识是否启动自动换肤
	private int year, month, day, hours, minute, second;// 年月日,小时分和秒的定义
	private Calendar c;// 日历
	Handler handler;
	Timer timer;
	TimerTask task;
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setProgressBarVisibility(true); // 设置进度条可见
		setContentView(R.layout.mainshow);
		huanfu=true;
		preferences = getSharedPreferences("zidonghuanfu", MODE_PRIVATE);
		c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		hours = c.get(Calendar.HOUR_OF_DAY);
		// System.out.println(hours+"原来的值为24进制的数,所以要修改");
		minute = c.get(Calendar.MINUTE);
		second = c.get(Calendar.SECOND);
		// 找到主界面的id,为后续换背景做准备
		relalayout = (RelativeLayout) findViewById(R.id.relalayout);
		relalayout.setBackgroundResource(huanfuid[0]);
		// 初始化NotificationManager对象
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// 点击通知时转移内容
		intent = new Intent(getApplicationContext(), MainShow.class);
		// 主要设置点击通知的时显示内容的类
		pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
				intent, 0);
		// 构造Notification对象
		notification = new Notification();

		// 删除之前定义的通知,(通知用户该软件正在后台运行)
		// 启动后删除之前我们定义的通知
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(0);

		// 禁止输入法自动弹出
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		am = ActivityManager1.getInstance(); // 获得ActivityManager的实例
		am.addActivity(this);// 添加Activity到ActivityManager里面
		alm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		btnshezhi = (Button) findViewById(R.id.btnSheZhi);// 设置按钮
		btnChangeSkin = (Button) findViewById(R.id.btnChangeSkin);// 点击换肤
		btnyaoyiyao = (Button) findViewById(R.id.btnyaoyiyao);
		btnGuang = (Button) findViewById(R.id.btnGuang);
		btnAdd = (Button) findViewById(R.id.btnAdd); // 添加记录按钮
		btnFirst = (Button) findViewById(R.id.btnFirst); // 首页按钮
		btnPre = (ImageButton) findViewById(R.id.btnPre);// 上一页按钮
		btnNext = (ImageButton) findViewById(R.id.btnNext);// 下一页按钮
		btnEnd = (Button) findViewById(R.id.btnEnd);// 末页按钮
		m_ProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		m_ProgressBar.setIndeterminate(false);// ProgressBar
												// 设置成”indeterminate”//
												// 模式,此时进度条可以显示一个不断转动的滚轮或是一个水平的进度条。
		lv = (ListView) findViewById(R.id.listview);
		sd = new SqliteDBConnect(MainShow.this);

		fenye();// 分页显示记录方法
		// 当用户点击记录列表项,激发该事件
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Map<String, Object> map = (Map<String, Object>) arg0
						.getItemAtPosition(arg2);
				// 进入显示具体记事内容的界面 Look.java
				Intent intent = new Intent();
				intent.putExtra("noteId", map.get("noteId").toString());
				intent.setClass(MainShow.this, Look.class);
				startActivity(intent);
			}
		});
		// 当用户长按某个记录项时,激发该事件
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				final Map<String, Object> map = (Map<String, Object>) arg0
						.getItemAtPosition(arg2);
				AlertDialog.Builder adb = new Builder(MainShow.this);
				adb.setTitle(map.get("noteName").toString());
				adb.setItems(new String[] { "删 除", "修 改" },
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									SQLiteDatabase sdb = sd
											.getReadableDatabase();
									sdb.delete("note", "noteId=?",
											new String[] { map.get("noteId")
													.toString() });
									Toast.makeText(MainShow.this, "删除成功",
											Toast.LENGTH_SHORT).show();
									sdb.close();
									fenye();
									break;
								case 1:
									// 当用户选择了修改选项功能项时,启动Update的界面
									Intent intent = new Intent();
									intent.putExtra("noteId", map.get("noteId")
											.toString());
									intent.setClass(MainShow.this, Update.class);
									startActivity(intent);
									break;
								}
							}
						});
				adb.show();
				return false;
			}
		});
		btnshezhi.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainShow.this, Settings.class);
				//startActivity(intent);
				startActivityForResult(intent, 2);
			}
		});
		// 为摇一摇按钮注册事件监听器
		btnyaoyiyao.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainShow.this, SensorTestActivity.class);
				startActivity(intent);
			}
		});
		// 为光传感器事件添加事件监听器
		btnGuang.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(MainShow.this, guangchuanganqiSersor.class);
				startActivity(intent);
			}
		});
		// 为添加按钮注册事件监听器
		btnAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				m_ProgressBar.setVisibility(View.VISIBLE);
				m_ProgressBar.setProgress(0);
				Intent intent = new Intent();
				intent.setClass(MainShow.this, ActivityMain.class);
				startActivity(intent);
			}
		});

		btnFirst.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (page_no == 1) {
					Toast.makeText(MainShow.this, "已经是首页了", Toast.LENGTH_SHORT)
							.show();
				} else {
					page_no = 1;
				}
				fenye();
			}
		});
		btnNext.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (page_no == page_count) {
					Toast.makeText(MainShow.this, "已经是末页了", Toast.LENGTH_SHORT)
							.show();
				} else {
					page_no += 1;
				}
				fenye();
			}
		});
		btnPre.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (page_no == 1) {
					Toast.makeText(MainShow.this, "已经是首页了", Toast.LENGTH_SHORT)
							.show();
				} else {
					page_no -= 1;
				}
				fenye();
			}
		});
		btnEnd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (page_no == page_count) {
					Toast.makeText(MainShow.this, "已经是末页了", Toast.LENGTH_SHORT)
							.show();
				} else {
					page_no = page_count;
				}
				fenye();
			}
		});
	}

	// 换肤按钮添加点击事件
	public void setbackground(View view) {
		Intent intent = new Intent(this, ImageGallery.class);
		startActivityForResult(intent, 1);
	}

	// 从sd中选中图片,设置为背景
	@SuppressWarnings("deprecation")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == 12) {
			Bundle bundle = data.getExtras();
			String url = bundle.getString("url");
			Uri uri = Uri.parse(url);
			relalayout.setBackgroundDrawable(Drawable.createFromPath(uri
					.getPath()));
		}else if (requestCode == 2 && resultCode == 11) {
			Bundle bundle = data.getExtras();
			huanfu = bundle.getBoolean("bo");
			System.out.println("测试是否执行该句的得到换肤数据"+huanfu);
			if(huanfu == true){
	    		// 定时更换主界面Mainshow.java的背景
	    		handler = new Handler() {
	    			public void handleMessage(Message msg) {
	    				super.handleMessage(msg);
	    				if (msg.what == 1) {
	    					relalayout.setBackgroundResource(huanfuid[currentpifu++% huanfuid.length]);
	    				}
	    			}
	    		};
	    		timer = new Timer(true);
	    		// 任务
	    		task = new TimerTask() {
	    			public void run() {
	    				Message msg = new Message();
	    				msg.what = 1;
	    				handler.sendMessage(msg);
	    			}
	    		};
	    		// 启动定时器,每隔10秒更换背景
	    		timer.schedule(task, 0, 1 * 10 * 1000);
				//relalayout.setBackgroundResource(huanfuid[2]);
			} else if(huanfu == false){
//消除定时器
				handler.removeCallbacksAndMessages(null);
				 if (task != null) {
					 task.cancel();
					 task = null;
		     }
		     if (timer != null) {
		    	 timer.cancel();
		    	 timer.purge();
		    	 timer = null;
		     }
				relalayout.setBackgroundResource(huanfuid[3]);
			}
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, "设置铃声");
		menu.add(0, 2, 2, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		// 转到闹钟view
		case 1:
			Intent intent = new Intent();
			intent.setClass(MainShow.this, SetAlarm.class);
			startActivity(intent);
			break;

		case 2:
			AlertDialog.Builder adb2 = new Builder(MainShow.this);
			adb2.setTitle("消息");
			adb2.setMessage("真的要退出吗?");
			adb2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// am.exitAllProgress();
					// 杀死所有进程
					Intent startMain = new Intent(Intent.ACTION_MAIN);
					startMain.addCategory(Intent.CATEGORY_HOME);
					startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(startMain);
					// System.exit(0);
					// android.os.Process.killProcess(android.os.Process.myPid());
				}
			});
			adb2.setNegativeButton("取消", null);
			adb2.show();
			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { //
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}


	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}

	};


}
   其他功能的代码块,读者可以删除掉,这里我就不删除了,请高手指教,谢谢。转载请注明出处:
http://blog.csdn.net/nihaoqiulinhe/article/details/17333439

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:撸撸猫 设计师:马嘣嘣 返回首页

打赏作者

清澈@Cherry

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值