Galaxy S4 提取温湿度 APP
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"><?xml version="1.0" encoding="utf-8"?></span>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/AppLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/spring"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_width="150dp"
android:layout_height="match_parent">
<ImageView
android:id="@+id/MainActtempImage"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="@+id/MainActCurTStr"
android:textSize="48sp"
android:text="@string/currentTemp" />
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_width="150dp"
android:layout_height="match_parent">
<ImageView
android:id="@+id/MainActtempImage1"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="48sp"
android:id="@+id/MainActCurHStr"
android:text="@string/currentTemp" />
</LinearLayout>
</LinearLayout>
<!-- 显示城市的天气 没有实现-->
<LinearLayout
android:gravity="center_horizontal"
android:orientation="horizontal"
android:layout_width="150dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="24sp"
android:text="@string/City" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="@+id/CityText"
android:textSize="24sp"
android:text="@string/currentTemp" />
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:orientation="horizontal"
android:layout_width="150dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="24sp"
android:text="@string/OutTemp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="@+id/OutTempText"
android:textSize="24sp"
android:text="@string/currentTemp" />
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:orientation="horizontal"
android:layout_width="150dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="24sp"
android:text="@string/OutHer" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="@+id/OutHerText"
android:textSize="24sp"
android:text="@string/currentTemp" />
</LinearLayout>
</LinearLayout>
//mainactivity.java
package com.example.tmmeter;
//import android.content.Context;
//import android.hardware.Sensor;
//import android.hardware.SensorEvent;
//import android.hardware.SensorEventListener;
//import android.hardware.SensorManager;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class MainActivity extends Activity {
private TextView TempText,TempText1,CityText,Ttext,Htext;
private ImageView ig,ig1;
private SensorManager mSensorManager;
private int season;
private int ShowFflag;
private SensorEventListener mSensorListener;
private Sensor mSensor,mSensor1;
<span style="white-space:pre"> </span>private LinearLayout myLayout;
<span style="white-space:pre"> </span>private Resources resources;
private Drawable dw;
private float value = -999f;
private String fileString;
private String Wether[];
// private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//load layout
setContentView(R.layout.activity_main);
//initial layout item
init();
//apply a system service
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
//if(mSensorManager == null) System.out.println("get sensor Manager fail");
//else{System.out.println("get sensor Manager Success");}
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY );
mSensor1 = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
//
mSensorListener = new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
value= event.values[0];
SetTempText(0);
}
else if(event.sensor.getType() == Sensor.TYPE_RELATIVE_HUMIDITY){
value =event.values[0];
SetTempText(1);
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent=new Intent();
intent.setClass(MainActivity.this, TempMenuActivity.class);
intent.putExtra(ConstUtil.SEASON_KEY, season);
intent.putExtra(ConstUtil.F_FLAG, ShowFflag);
startActivityForResult(intent,ConstUtil.RESULT_CODE);
return true;
case R.id.action_quit:
finish();
//android.os.Process.killProcess(android.os.Process.myPid());
return true;
}
return false;
}
private void init() {
Wether = new String[4];
TempText = (TextView) findViewById(R.id.MainActCurTStr);
TempText1 = (TextView)findViewById(R.id.MainActCurHStr);
CityText = (TextView)findViewById(R.id.CityText);
Ttext = (TextView)findViewById(R.id.OutTempText);
Htext = (TextView)findViewById(R.id.OutHerText);
int[] flagArray=new int[9];
String tempString = "";
TempText.setText(tempString);
TempText1.setText(tempString);
ig = (ImageView) findViewById(R.id.MainActtempImage);
ig.setImageResource(R.drawable.tempbg);
ig1 = (ImageView) findViewById(R.id.MainActtempImage1);
ig1.setImageResource(R.drawable.shuidi);
fileString = ConstUtil.OpenSdcardFile();
if(fileString!=null){
//Log.i("TestFile", "read SDcard file is success");
flagArray =ConstUtil.phraseString(fileString);
season=flagArray[ConstUtil.LISTITEM9];
ShowFflag=flagArray[ConstUtil.LISTITEM1];
}
else Log.i("TestFile", "read SDcard file is fail");
if (isNetworkAvailable()) {
Wether= getWeather();
//CityText.setText(Wether[0]);
//Ttext.setText(Wether[1]);
//Htext.setText(Wether[2]);
}else{
showDialog();
}
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(mSensorListener, mSensor1, SensorManager.SENSOR_DELAY_NORMAL);
SetLayoutBG();
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode == ConstUtil.RESULT_CODE){
int var = data.getExtras().getInt(ConstUtil.SEASON_KEY);
ShowFflag = data.getExtras().getInt(ConstUtil.F_FLAG);
if(var != season){
season =var;
SetLayoutBG();
}
SetTempText(0);
}
}
public void SetTempText(int flag){
switch(flag){
case 0:
if(ShowFflag==1){
value = value*9/5+32;
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(1,4);
value = bd.floatValue();
TempText.setText("温度\n"+value+"F");
}
else{
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(1,4);
value = bd.floatValue();
TempText.setText("温度\n"+value+"℃");
}break;
case 1:
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(1,4);
value = bd.floatValue();
TempText1.setText("湿度\n"+value+"%");
break;
default:
break;
}
}
public void SetLayoutBG(){
resources= getBaseContext().getResources();
myLayout = (LinearLayout)findViewById(R.id.AppLayout);
switch(season){
case ConstUtil.SEASON_SPRINT:
dw= resources.getDrawable(R.drawable.spring);
myLayout.setBackground(dw);
break;
case ConstUtil.SEASON_SUMMER:
dw= resources.getDrawable(R.drawable.summer);
myLayout.setBackground(dw);
break;
case ConstUtil.SEASON_AUTUMN:
dw= resources.getDrawable(R.drawable.autumn);
myLayout.setBackground(dw);
break;
case ConstUtil.SEASON_WINTER:
dw= resources.getDrawable(R.drawable.winter);
myLayout.setBackground(dw);
break;
default: break;
}
}
private boolean isNetworkAvailable() {
ConnectivityManager mgr = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = mgr.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
private void showDialog() {
// TODO Auto-generated method stub
/* create ui */
final AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示").setMessage("WiFi连接不可用");
builder.setPositiveButton("前往打开wifi", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Intent go2wifi = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
go2wifi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(go2wifi);
}
})
.setNegativeButton("下次再说", null);
dialog = builder.create();
dialog.getWindow()
.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
dialog.show(); /* set size & pos */
//WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
//Display display = wm.getDefaultDisplay();
/*if (display.getHeight() > display.getWidth()) {
// lp.height = (int) (display.getHeight() * 0.5);
lp.width = (int) (display.getWidth() * 1.0);
} else {
// lp.height = (int) (display.getHeight() * 0.75);
lp.width = (int) (display.getWidth() * 0.5);
}
dialog.getWindow().setAttributes(lp); */
}
private String[] getWeather() {
String[] Strbuffer= new String[4];
try
{
URL url = new URL("http://m.weather.com.cn/data/101280601.html");
InputStream is = url.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String info = bos.toString("utf-8");
JSONObject dataJson = new JSONObject(info);
JSONObject json = dataJson.getJSONObject("weatherinfo");
Strbuffer[0] = json.getString("city");
Strbuffer[1] = json.getString("temp1");
Strbuffer[2] = json.getString("weather1");
Strbuffer[3] = json.getString("img1");
System.out.println(Strbuffer[0]);is.close();bos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return Strbuffer;
}
}
//子菜单xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/menuListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1"
>
</ListView>
</LinearLayout>
//listview item1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/listview_title"
android:background="#FF008040"
>
<TextView
android:id="@+id/title_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:textIsSelectable="false"
android:text="@string/AppTitle"
android:textSize="16sp"
/>
</LinearLayout>
//listview item2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/listview_title1"
android:background="#FF10FF80"
>
<TextView
android:id="@+id/title_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:textIsSelectable="false"
android:text="@string/MenuTitle"
android:textSize="16sp"
/>
</LinearLayout>
子菜单java
package com.example.tmmeter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class TempMenuActivity extends Activity {
private List<Map<String , String>> listdata;
private ListView menuLv;
private ListAdapter menuLvAdapter;
int scroll_num = 10;
ViewHolder holder;
ViewHolder1 holder1;
ArrayList<Map<String, String>> data;
HashMap<Integer,Boolean> isSelected;
MyAdapter adapter;
private Bundle b;
private int season;
private RadioGroup raGroup1;
private int ShowFflag;
private int flashScreen;
private Drawable dw;
private Resources resources;
private LinearLayout myLayout;
private String[] ItemStr = new String[] {
"温度计","设置",
"显示华氏度","显示闪屏","显示帮助界面","解锁更新","屏幕待机",
"日期格式","自动更新","更新间隔","选择背景","关于"
};
private String[] ItemStr1 = new String[]{
"","",
"显示值显示华氏度","","每次打开软件显示","解锁更新桌面数据","设置屏幕超时时间",
"设置日期的显示格式","自动更新桌面数据","自动更新数据间隔时间","选择背景样式",""
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menusetting_layout);
menuLv= (ListView)findViewById(R.id.menuListView);
InitData();
InitListView();
menuLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch(arg2){
case ItemElement.ITEM_SHOWF:break;
case ItemElement.ITEM_FLASHSCREEN:break;
case ItemElement.ITEM_SHOWHELP:break;
case ItemElement.ITEM_LOCKUPDATE:break;
case ItemElement.ITEM_STANDBYTIME:break;
case ItemElement.ITEM_TIMEFORMAT:break;
case ItemElement.ITEM_AUTOUPDATE:break;
case ItemElement.ITEM_SELBG:
showSetBg();
break;
case ItemElement.ITEM_ABOUTAPP:
ShowAboutApp();
break;
default:break;
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_BACK){
b.putInt(ConstUtil.SEASON_KEY, season);
b.putInt(ConstUtil.F_FLAG, ShowFflag);
Intent MainIntent = new Intent();//(TempMenuActivity.this,MainActivity.class);
MainIntent.putExtras(b);
setResult(ConstUtil.RESULT_CODE,MainIntent);
if(OpenSdcardFile()) System.out.println("Write file success ");
else System.out.println("Write file fail ");
finish();
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public void onDestroy(){
super.onDestroy();
}
private void showSetBg(){
final CharSequence[] items = {"春","夏","秋","冬"};
final int beforeSeason;
AlertDialog.Builder dlg_builder = new AlertDialog.Builder(this);
dlg_builder.setTitle("设置背景图片");
beforeSeason = season;
dlg_builder.setSingleChoiceItems(items, season, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
season = which;
}
});
dlg_builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dlg_builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
season = beforeSeason;
}
});
AlertDialog dlg = dlg_builder.create();
dlg.getWindow().setGravity(Gravity.CENTER);
dlg.setCanceledOnTouchOutside(true);
dlg.show();
}
private void ShowAboutApp(){
final CharSequence str="此温度由sss设计!\n"+"软件版本V1.0\n"+"有问题请反馈到576791284@qq.com\n" +
"\n";
AlertDialog.Builder dlg_builder = new AlertDialog.Builder(this);
dlg_builder.setTitle("温度计");
AlertDialog dlg = dlg_builder.create();
dlg.setCanceledOnTouchOutside(true);
dlg.setMessage(str);
dlg.show();
}
private void SetItemFunc(int position,int checkFlag){
switch(position){
case ItemElement.ITEM_SHOWF: ShowFflag=checkFlag;break;
default: break;
}
}
public void InitListView1(){
SimpleAdapter adapter = new SimpleAdapter(this,
listdata,
android.R.layout.simple_list_item_2, // List 显示两行item1、item2
new String[]{ "TITLE", "CONTENT" },
new int[]{ android.R.id.text1, android.R.id.text2 }
);
menuLv.setAdapter(adapter);
}
public void InitData(){
listdata = new ArrayList<Map<String, String>>();
data = new ArrayList<Map<String, String>>();
for(int i=0; i<ItemStr.length; i++){
Map<String, String> Tempmap = new HashMap<String, String>();
Tempmap.put("TITLE", ItemStr[i]);
Tempmap.put("CONTENT",ItemStr1[i]);
listdata.add(Tempmap);
data.add(Tempmap);
}
b=getIntent().getExtras();
season= b.getInt(ConstUtil.SEASON_KEY);
ShowFflag = b.getInt(ConstUtil.F_FLAG);
myLayout = (LinearLayout)findViewById(R.id.setMenu);
resources= getBaseContext().getResources();
}
public void InitListView(){
adapter = new MyAdapter(data,TempMenuActivity.this);
menuLv.setAdapter(adapter);
}
public boolean OpenSdcardFile(){
String res="";
String sdStatus = Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
Log.d("TestFile", "SD card is not avaiable/writeable right now.");
return false;
}
try {
String fileName="sensor.txt";
String pathName="/sdcard/sensorFors4/";
File path = new File(pathName);
File file = new File(pathName + fileName);
if( !path.exists()) {
Log.i("TestFile", "Create the path:" + pathName);
path.mkdir();
}
if(!file.exists()) {
Log.i("TestFile", "Create the file:" + fileName);
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
res =CreateFile();
byte[] midbytes=res.getBytes("UTF8");
stream.write(midbytes);
stream.close();
return true;
} catch(Exception e) {
Log.e("TestFile", "Error on writeFilToSD.");
e.printStackTrace();
}
return false;
}
public String CreateFile(){
String retStr="";
String showf;
String selbackflag;
showf=String.valueOf(ShowFflag);
selbackflag=String.valueOf(season);
retStr ="$1showfflag:"+showf+"\n"+
"$2flashscreenflag:1"+"\n"+
"$32showhelpflag:1"+"\n"+
"$4lockupdateflag:1"+"\n"+
"$5standbytimeoutflag:1"+"\n"+
"$6dateformatflag:1"+"\n"+
"$7autoupdateflag:1"+"\n"+
"$8updatetimeflag:1"+"\n"+
"$9selbackflag:"+selbackflag+"\n";
return retStr;
}
class MyAdapter extends BaseAdapter{
int count = scroll_num;
Context mContext;
List<Map<String, String>> mData;
LayoutInflater mInflater;
public MyAdapter(ArrayList<Map<String, String>>data,Context context) {
this.mContext = context;
this.mData = data;
mInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
if(count>mData.size()){
count = mData.size();
}
isSelected = new HashMap<Integer,Boolean>();
for(int i = 0; i<data.size(); i++){
isSelected.put(i, false);
}
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(position ==0){
return mInflater.inflate(R.layout.listview_title, null);
}
if(position == 1){
return mInflater.inflate(R.layout.listview_title1, null);
}
if( (position ==ItemElement.ITEM_STANDBYTIME ||position ==ItemElement.ITEM_TIMEFORMAT ) ||
(position >=ItemElement.ITEM_UPDATEINTERVAL && position<= ItemElement.ITEM_ABOUTAPP) ){
if(convertView == null){
convertView = mInflater.inflate(R.layout.item_listview1, null);
holder1 = new ViewHolder1();
holder1.title = (TextView) convertView.findViewById(R.id.item_listview_title1);
holder1.content = (TextView) convertView.findViewById(R.id.item_listview_content1);
convertView.setTag(holder1);
}else{
holder1 = (ViewHolder1) convertView.getTag();
}
holder1.title.setText(data.get(position).get("TITLE").toString());
holder1.content.setText(data.get(position).get("CONTENT").toString());
return convertView;
}
else{
if(convertView == null){
convertView = mInflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item_listview_title);
holder.content = (TextView) convertView.findViewById(R.id.item_listview_content);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.item_listview_checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(data.get(position).get("TITLE").toString());
holder.content.setText(data.get(position).get("CONTENT").toString());
if(position == ItemElement.ITEM_SHOWF){
if(ShowFflag ==1){
holder.checkBox.setChecked(true);
isSelected.put(position, true);
}
else {
holder.checkBox.setChecked(false);
isSelected.put(position, false);
}
}
else
holder.checkBox.setChecked(isSelected.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isSelected.get(position)){
isSelected.put(position, false);
Log.i("CheckBox","unChecked ");
SetItemFunc(position,0);
}
else {
isSelected.put(position, true);
Log.i("CheckBox","Checked ");
SetItemFunc(position,1);
}
}
});
return convertView;
}
}
}
class ViewHolder{
TextView title;
TextView content;
CheckBox checkBox;
}
class ViewHolder1{
TextView title;
TextView content;
}
}
class ItemElement{
public final static int ITEM_SHOWF=2;
public final static int ITEM_FLASHSCREEN=3;
public final static int ITEM_SHOWHELP =4;
public final static int ITEM_LOCKUPDATE=5;
public final static int ITEM_STANDBYTIME =6;
public final static int ITEM_TIMEFORMAT = 7;
public final static int ITEM_AUTOUPDATE = 8;
public final static int ITEM_UPDATEINTERVAL= 9;
public final static int ITEM_SELBG = 10;
public final static int ITEM_ABOUTAPP = 11;
}
常量类
package com.example.tmmeter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.http.util.EncodingUtils;
import android.os.Environment;
import android.util.Log;
public class ConstUtil {
public final static int SEASON_SPRINT=0;
public final static int SEASON_SUMMER=1;
public final static int SEASON_AUTUMN =2;
public final static int SEASON_WINTER=3;
public final static int RESULT_CODE =0;
public final static String filePath= "/sdcard/sensorFors4/";
public final static String fileName= "sensor.txt";
public final static String SEASON_KEY = "SEASON";
public final static String F_FLAG ="SHOWF";
public final static String SERVICE_KEY ="SERVICEKEY";
public final static String FILE_VAR1 = "season";
public final static String FILE_VAR2 = "showfflag";
public final static int MAIN_SERVICE=1;
public final static int APPWD_SERVICE=2;
public final static int LISTITEM1=0;
public final static int LISTITEM2=1;
public final static int LISTITEM3=2;
public final static int LISTITEM4=3;
public final static int LISTITEM5=4;
public final static int LISTITEM6=5;
public final static int LISTITEM7=6;
public final static int LISTITEM8=7;
public final static int LISTITEM9=8;
public final static String defaultFile="$1showfflag:0"+"\n"+
"$2flashscreenflag:1"+"\n"+
"$32showhelpflag:1"+"\n"+
"$4lockupdateflag:1"+"\n"+
"$5standbytimeoutflag:1"+"\n"+
"$6dateformatflag:1"+"\n"+
"$7autoupdateflag:1"+"\n"+
"$8updatetimeflag:1"+"\n"+
"$9selbackflag:1"+"\n";
final static String OpenSdcardFile(){
String res="";
String sdStatus = Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
Log.d("TestFile", "SD card is not avaiable/writeable right now.");
return null;
}
try {
File path = new File(ConstUtil.filePath);
File file = new File(ConstUtil.filePath + ConstUtil.fileName);
if( !path.exists()) {
Log.i("TestFile", "Create the path:" + ConstUtil.filePath);
path.mkdir();
}
if(!file.exists()) {
Log.i("TestFile", "Create the file:" + ConstUtil.fileName);
file.createNewFile();
FileOutputStream stream = new FileOutputStream(file);
res =ConstUtil.defaultFile;
byte[] midbytes=res.getBytes("UTF8");
stream.write(midbytes);
stream.close();
}
FileInputStream stream = new FileInputStream(file);
int length = stream.available();
byte [] buffer = new byte[length];
stream.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
stream.close();
return res;
} catch(Exception e) {
Log.e("TestFile", "Error on ReadFilToSD."+e.toString());
e.printStackTrace();
}
return null;
}
final static int[] phraseString(String fileString){
int i,count=0;//count1=0;
int []var = new int[9];
char ch =':';
for(i=0;i<fileString.length();i++){
if(fileString.charAt(i) == ch){
if(count>=9) break;
String IntStr = fileString.substring(i+1, i+2);
var[count++] = Integer.parseInt(IntStr);
}
}
return var;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tmmeter"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".SensorAppWidget"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_provider"
/>
</receiver>
<activity
android:name="com.example.tmmeter.WelcomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainActivity"></activity>
<activity android:name="SettingMenuActivity"></activity>
<activity android:name="TempMenuActivity"></activity>
<service android:name="SensorService"></service>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sensoreWidget"
android:background="@drawable/spring"
android:gravity="center_horizontal"
android:orientation="vertical" >
<Button
android:id="@+id/yunduoImage"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="时间"
android:textSize="18sp"
android:textColor="#FF00FF00"
android:background = "@drawable/yunduo"
android:gravity="center"
/>
<LinearLayout
android:gravity="center_horizontal"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:textIsSelectable="false"
android:id="@+id/WidgetString"
android:textColor="#FF505050"
android:textSize="24sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center_horizontal"
android:text="@string/SpaceString"
<pre name="code" class="html" style="font-size: 11.8181819915771px;"> <span style="white-space:pre"> </span>android:textSize="24sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:textSize="24sp"
android:textColor="#FF505050"
android:textIsSelectable="false"
android:id="@+id/WidgetString1"/>
</LinearLayout>
</LinearLayout>
//
</pre><pre code_snippet_id="549461" snippet_file_name="blog_20141211_15_9802813" name="code" class="html">//<pre name="code" class="plain" style="font-size: 11.8181819915771px;">//SensorAppWidget.java
<pre name="code" class="plain">package com.example.tmmeter;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
public class SensorAppWidget extends AppWidgetProvider {
private Intent intent;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// System.out.println("onUpdate");
intent = new Intent(context, SensorService.class);
context.startService(intent);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
//System.out.println("onDeleted");
if(intent!=null)
context.stopService(intent);
else {System.out.println("Intent is null ");}
super.onDeleted(context, appWidgetIds);
}
@Override
public void onDisabled(Context context) {
//System.out.println("onDisabled");
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context,
SensorAppWidget.class) , PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
super.onDisabled(context);
}
@Override
public void onEnabled(Context context) {
//System.out.println("onEnabled");
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context,
SensorAppWidget.class) , PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
super.onEnabled(context);
}
@Override
public void onReceive(Context context, Intent intent){
//System.out.println("onReceive");
super.onReceive(context, intent);
}
}
//SensorService.java
package com.example.tmmeter;
import java.math.BigDecimal;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
public class SensorService extends Service {
private RemoteViews remoteViews;
final static int UPDATE=0x168;
final static int UPDATA1=0x169;
final static int UPDATA2=0x170;
private float value = -999f,value1=0.5f;
private String TString,HString;
private SensorEventListener mSensorListener;
private Sensor mSensor,mSensor1;
private SensorManager mSensorManager;
private int ShowFflag;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("SensorService create ");
remoteViews = new RemoteViews(getApplication().getPackageName(), R.layout.sensorwidgetlayout);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.yunduoImage, pendingIntent);
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY );
mSensor1 = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
mSensorListener = new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
value= event.values[0];
Message msg = handler.obtainMessage();
msg.what = UPDATA1;
handler.sendMessage(msg);
//System.out.println("running temp =============>");
}
else if(event.sensor.getType() == Sensor.TYPE_RELATIVE_HUMIDITY){
value1 =event.values[0];
Message msg = handler.obtainMessage();
msg.what = UPDATA2;
handler.sendMessage(msg);
// System.out.println("running hvalue =============>");
}
}
};
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.what = UPDATE;
handler.sendMessage(msg);
//System.out.println("running =============>");
}
}, 1, 1000);//
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE:
updateDate(1);
break;
case UPDATA1:
updateDate(2);
break;
case UPDATA2:
updateDate(3);
break;
default: break;
}
}
};
private BroadcastReceiver mTimePickerBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// updateTime();
}
};
private void updateDate(int flag){
if(flag == 1){
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String str = formatter.format(curDate);
remoteViews.setTextViewText(R.id.yunduoImage, str);
}
else if(flag == 2){
String sign="";
if(ShowFflag ==1){
value = value*9/5+32;
sign ="F";
}else sign ="℃";
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(1,4);
value = bd.floatValue();
TString = ""+value+sign;
remoteViews.setTextViewText(R.id.WidgetString, TString);
}else if(flag ==3){
BigDecimal bd = new BigDecimal(value1);
bd = bd.setScale(1,4);
value1 = bd.floatValue();
HString = ""+value1+"%";
remoteViews.setTextViewText(R.id.WidgetString1, HString);
}
else return ;
ComponentName componentName = new ComponentName(getApplication(),
SensorAppWidget.class);
AppWidgetManager.getInstance(getApplication()).updateAppWidget(
componentName, remoteViews);
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
IntentFilter updateIntent = new IntentFilter();
updateIntent.addAction("android.intent.action.TIME_TICK");
registerReceiver(mTimePickerBroadcast, updateIntent);
mSensorManager.registerListener(mSensorListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(mSensorListener, mSensor1, SensorManager.SENSOR_DELAY_NORMAL);
String fileString = ConstUtil.OpenSdcardFile();
if(fileString !=null){
ShowFflag = ConstUtil.phraseString(fileString)[ConstUtil.LISTITEM1];
}
System.out.println("Strart service");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent){
System.out.println("on Unbind");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
// 注销系统的这个广播
unregisterReceiver(mTimePickerBroadcast);
//Intent intent = new Intent(getApplicationContext(), SensorService.class);
//getApplication().startService(intent);
System.out.println("remove service");
super.onDestroy();
}
}
//增加开始界面
<pre name="code" class="plain"><pre code_snippet_id="549461" snippet_file_name="blog_20141211_19_8288834" name="code" class="html" style="font-size: 11.8181819915771px;">XML
<pre name="code" class="plain"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_vertical|center_horizontal">
<ImageView
android:id="@+id/welcome_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/welcome1"
/>
</LinearLayout>
java
<span style="font-size:14px;"><span style="white-space: normal;"></span></span><pre name="code" class="plain">package com.example.tmmeter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class WelcomeActivity extends Activity implements AnimationListener {
private ImageView imageView = null;
private Animation alphaAnimation = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.welcome_page);
imageView = (ImageView)findViewById(R.id.welcome_image_view);
alphaAnimation = AnimationUtils.loadAnimation(this, R.xml.welcome_alpha);
alphaAnimation.setFillEnabled(true); //启动Fill保持
alphaAnimation.setFillAfter(true); //设置动画的最后一帧是保持在View上面
imageView.setAnimation(alphaAnimation);
alphaAnimation.setAnimationListener(this); //为动画设置监听
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//动画结束时结束欢迎界面并转到软件的主界面
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//在欢迎界面屏蔽BACK键
if(keyCode==KeyEvent.KEYCODE_BACK) {
return false;
}
return false;
}
}
///破代码,占内存,要优化!