特手天氣

1運行圖片

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

開發中用到心知天氣的jar包https://www.seniverse.com/doc#code

2建立佈局activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/sun_background"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:layout_weight="1"
        android:id="@+id/vp_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>
</LinearLayout>

3建立activity_add_city.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="#5B5B5A"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/iv_add_back"
            android:src="@mipmap/title_bar_back_btn"
            android:layout_width="60dp"
            android:layout_height="60dp" />
        <TextView
            android:textSize="20sp"
            android:textColor="@android:color/white"
            android:gravity="center"
            android:text="添加城市"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

   <Button
       android:textColor="@android:color/white"
       android:layout_gravity="center"
       android:id="@+id/add_btn_select_city"
       android:text="選擇城市"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:paddingLeft="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:textColor="@android:color/white"
                android:text="熱門城市"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:padding="10dp"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                style="@style/item_LinearLayout">
                <TextView
                    android:id="@+id/city11"
                    android:text="北京"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city12"
                    android:text="上海"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city13"
                    android:text="廣州"
                    style="@style/item_TextView" />
            </LinearLayout>
            <LinearLayout
                style="@style/item_LinearLayout">
                <TextView
                    android:id="@+id/city21"
                    android:text="深圳"
                    style="@style/item_TextView"/>
                <TextView
                    android:id="@+id/city22"
                    android:text="武漢"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city23"
                    android:text="南京"
                    style="@style/item_TextView" />
            </LinearLayout>
            <LinearLayout
                style="@style/item_LinearLayout">
                <TextView
                    android:id="@+id/city31"
                    android:text="杭州"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city32"
                    android:text="西安"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city33"
                    android:text="鄭州"
                    style="@style/item_TextView" />
            </LinearLayout>
            <LinearLayout
                style="@style/item_LinearLayout">
                <TextView
                    android:id="@+id/city41"
                    android:text="成都"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city42"
                    android:text="東莞"
                    style="@style/item_TextView" />
                <TextView
                    android:id="@+id/city43"
                    android:text="瀋陽"
                    style="@style/item_TextView"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <TextView
        android:layout_marginLeft="20dp"
        android:textColor="@android:color/white"
        android:text="已有城市"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ListView
        android:layout_marginTop="20dp"
        android:id="@+id/add_lv_listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>

4建立add_city_item.xml。activity_add_city中listView中的每行佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
    <TextView
        android:layout_marginLeft="40dp"
        android:id="@+id/add_item_tv_name"
        android:textSize="25dp"
        android:layout_weight="1"
        android:textColor="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <ImageView
        android:id="@+id/add_item_iv_delect"
        android:src="@mipmap/delete"
        android:layout_width="30dp"
        android:layout_height="30dp" />
</LinearLayout>

5建立fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <ImageView
            android:padding="10dp"
            android:src="@mipmap/ic_title_add"
            android:id="@+id/top_iv_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <LinearLayout
            android:padding="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:src="@mipmap/ic_location_ford"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TextView
                android:text="地點"
                android:id="@+id/top_tv_title"
                android:textColor="@android:color/white"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <ImageView
            android:padding="10dp"
            android:src="@mipmap/ic_title_share"
            android:id="@+id/top_iv_copy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="340dp"></LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_update_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingLeft="20dp"
                    android:text="14:24 發佈"
                    android:textColor="@android:color/white" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:paddingLeft="20dp">

                    <TextView
                        android:id="@+id/tv_temperature"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="25°"
                        android:textColor="@android:color/white"
                        android:textSize="70sp" />

                    <TextView
                        android:id="@+id/tv_weather_case"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="多雲"
                        android:textColor="@android:color/white"
                        android:textSize="20sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:paddingLeft="20dp">

                    <ImageView
                        android:layout_width="25dp"
                        android:layout_height="25dp"
                        android:paddingRight="5dp"
                        android:src="@mipmap/ic_main_wind_es" />

                    <TextView
                        android:id="@+id/tv_wind"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="2級"
                        android:textColor="@android:color/white" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:paddingTop="10dp">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:paddingLeft="20dp">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:orientation="horizontal">

                            <TextView
                                android:id="@+id/tv_time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="今天"
                                android:textColor="@android:color/white" />

                            <TextView
                                android:id="@+id/tv_air_index"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="2"
                                android:background="@mipmap/btn_warn_alert_yellow"
                                android:paddingLeft="5dp"
                                android:text=" 79良好  "
                                android:textColor="@android:color/white" />

                            <ImageView
                                android:id="@+id/iv_cloud"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:paddingLeft="20dp"
                                android:src="@mipmap/ic_coollife_overcast_big" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:orientation="horizontal">

                            <TextView
                                android:id="@+id/tv_today_temperature"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="18~25℃"
                                android:textColor="@android:color/white" />

                            <TextView
                                android:id="@+id/tv_today_cloud"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:paddingLeft="15dp"
                                android:text="多雲轉晴"
                                android:textColor="@android:color/white" />
                        </LinearLayout>
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:orientation="horizontal">

                            <TextView
                                android:id="@+id/tv_tomorrow_time"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="明天"
                                android:textColor="@android:color/white" />

                            <TextView
                                android:id="@+id/tv_tomorrow_air_index"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:background="@mipmap/btn_warn_alert_yellow"
                                android:paddingLeft="5dp"
                                android:text=" 85優秀  "
                                android:textColor="@android:color/white" />

                            <ImageView
                                android:id="@+id/iv_tomorrow_cloud"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:paddingLeft="20dp"
                                android:src="@mipmap/ic_coollife_cloudy_big" />
                        </LinearLayout>

                        <LinearLayout
                            android:paddingTop="5dp"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:orientation="horizontal">

                            <TextView
                                android:id="@+id/tv_tomorrow_temperature"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="18~25℃"
                                android:textColor="@android:color/white" />

                            <TextView
                                android:id="@+id/tv_tomorrow_cloud"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:paddingLeft="15dp"
                                android:text="多雲轉晴"
                                android:textColor="@android:color/white" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
                    <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <TextView
                            android:layout_marginTop="10dp"
                            android:layout_marginBottom="10dp"
                            android:text="今天天氣趨勢"
                            android:layout_gravity="center"
                            android:textColor="@android:color/white"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" />
                        <HorizontalScrollView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent">
                            <LinearLayout
                                android:layout_width="wrap_content"
                                android:layout_height="match_parent"
                                android:orientation="vertical" >
                                <com.example.administrator.zfweather.myView.LineChartView
                                    android:id="@+id/line_chart"
                                    android:layout_width="1360dp"
                                    android:layout_height="180dp"
                                    android:paddingTop="10dp" />
                            </LinearLayout>
                        </HorizontalScrollView>
                    </LinearLayout>
                    <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <TextView
                            android:layout_marginBottom="10dp"
                            android:text="未來15天天氣趨勢"
                            android:layout_gravity="center"
                            android:textColor="@android:color/white"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content" />
                        <HorizontalScrollView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">
                            <LinearLayout
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:orientation="vertical" >
                                <com.example.administrator.zfweather.myView.FutureLineChartView
                                    android:id="@+id/future_line_chart"
                                    android:padding="10dp"
                                    android:layout_width="870dp"
                                    android:layout_height="400dp"
                                    android:paddingTop="10dp" />
                            </LinearLayout>
                        </HorizontalScrollView>
                    </LinearLayout>
                    <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <TextView
                            android:padding="10dp"
                            android:gravity="center"
                            android:textColor="@android:color/white"
                            android:textSize="15sp"
                            android:id="@+id/tv_body_temperature"
                            android:text="體感      19°"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                        <TextView
                            android:padding="10dp"
                            android:gravity="center"
                            android:textColor="@android:color/white"
                            android:textSize="15sp"
                            android:id="@+id/tv_humidity"
                            android:text="溼度       80%"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                        <TextView
                            android:padding="10dp"
                            android:gravity="center"
                            android:textColor="@android:color/white"
                            android:textSize="15sp"
                            android:id="@+id/tv_air_pressure"
                            android:text="氣壓       1006hpa"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                        <TextView
                            android:padding="10dp"
                            android:gravity="center"
                            android:textColor="@android:color/white"
                            android:textSize="15sp"
                            android:id="@+id/tv_visibility"
                            android:text="能見度    16km"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                        <TextView
                            android:padding="10dp"
                            android:gravity="center"
                            android:textColor="@android:color/white"
                            android:textSize="15sp"
                            android:id="@+id/tv_ultraviolet"
                            android:text="紫外線   最弱"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

6自定義佈局LineChartView實現二十四小時天氣預報趨勢圖

public class LineChartView extends View {

    private HistogramAnimation ani;


    int x, y, preX;

    private Paint titlePaint;// 繪製文本的畫筆

    private Paint linePaint;

    private Paint paint;// 矩形畫筆 柱狀圖的樣式信息

    private int[] text = new int[24];// 折線的轉折點

    Context contex;

    private String[] time = new String[24];

    private String[] wind = new String[24];

    private int[] windImaId = new int[24];

    private int min , max;

    private Bitmap mBitmap;
    // 座標軸底部的星期數

    private String[] str = new String[]{"1","2","3","4","5","6","7","8","9","10"};

    public LineChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.contex = context;
        init();
    }

    public LineChartView(Context context) {
        super(context);
        this.contex = context;
        init();
    }

    private void init(){

        initTemperature();
        initTime();
        initWind();
        initWindImgId();
        ani = new HistogramAnimation();
        ani.setDuration(0);
        titlePaint = new Paint();
       // startAnimation(ani);
    }

    private void initWindImgId(){
        for (int i = 0;i < 24; i++)
            windImaId[i] = R.mipmap.ic_main_wind_es;
    }

    private void initWind(){
        for (int i = 0;i < 24; i++)
            wind[i] =2 + "級";
    }
    public void initTime(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        String d = sdf.format(date);
        Integer integer = new Integer(d);
        for(int i = 0; i < 24; i++){
            if (integer < 10){
                time[i] = "0" + integer + ":00";
            }else time[i] = integer + ":00";
            integer = integer + 1;
            if(integer > 23)
                integer = 0;
        }
    }

    public void initTemperature(){
        int [] arrTemp= new int[]{20,20,18,20,22,20,20,20,23,20,20,20,20,20,20,22,20,20,20,21,20,20,20,24};
        min = max = arrTemp[0];
        for(int i :arrTemp){
            if(i > max){
                max = arrTemp[i];
            }
            if(i < min){
                min = arrTemp[i];
            }
        }
        if(min == max){
            min = min -5;
            max = max + 5;
        }
        max = max + 5;
        for (int i =0; i < arrTemp.length;i++){
            text [i] =  max - arrTemp[i]  ;
        }
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        linePaint = new Paint();

        titlePaint.setAntiAlias(true);
        Rect bundle2 = new Rect();

        int perWidth = 2000 / 24;
        int hPerHeight = getHeight() / 40;

        //畫圖片
        Drawable drawable;

        Path path = new Path();
        mBitmap = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
        Canvas mCancas = new Canvas(mBitmap);

        //畫縱座標
        for (int i = 1 ; i <= str.length   ; i++){
            titlePaint.setTextSize(sp2px(13));
            titlePaint.setColor(Color.WHITE);
            titlePaint.getTextBounds(str[i - 1],0,str[(i - 1)].length(),bundle2);
        }
        for (int i = 0; i< 24; i++){
            y = i * hPerHeight;
            //初始位置x 間隔
            x = i * (perWidth + 30) + dp2px(30);

            //畫折線
            if (i == 0) {
                path.moveTo(x, text[i] * hPerHeight);
            } else {
                path.lineTo(x, text[i] * hPerHeight);
            }

            linePaint.setColor(Color.parseColor("#bb2222"));
            linePaint.setAntiAlias(true);

            paint = new Paint();
            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(dp2px(1));

            //畫點
            mCancas.drawCircle(x, text[i] * hPerHeight, dp2px(3), linePaint);
            //畫圖片
            drawable = contex.getResources().getDrawable(windImaId[i]);
            drawable.setBounds(x -40,200,x -20,220);
            drawable.draw(canvas);

            mCancas.drawText(wind[i],x - 20, 220,titlePaint);

            mCancas.drawText(time[i],x - 40, 300,titlePaint);
            mCancas.drawText(max - text[i]  + "°",x - 20, text[i] * hPerHeight - 20,titlePaint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
            mCancas.drawPath(path, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
        paint.setStyle(Paint.Style.FILL);

        mCancas.drawRect(preX + dp2px(30), 0, getWidth(), getHeight(), paint);
        canvas.drawBitmap(mBitmap, 0, 0, null);
    }


    private int dp2px(int value){
        float v = getContext().getResources().getDisplayMetrics().density;
        return (int)(v * value + 0.5f);
    }

    private int sp2px(int value){
        float v = getContext().getResources().getDisplayMetrics().scaledDensity;
        return (int)(v * value + 0.5f);
    }

    private class HistogramAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if(interpolatedTime < 1.0f ){
                preX = (int)((getWidth() - dp2px(30)) * interpolatedTime);
            }else {
                preX = getWidth();
            }
            invalidate();
        }
    }
    public void start() {
        startAnimation(ani);
    }

}

7自定義佈局FutureLineChartView實現十五天天氣預報趨勢圖

public class FutureLineChartView extends View {

    private HistogramAnimation ani;

    boolean addData = false;

    int x, y, preX;

    private Paint titlePaint;// 繪製文本的畫筆

    private Paint linePaint;

    private Paint paint;// 矩形畫筆 柱狀圖的樣式信息

    private int[] hightText = new int[15];// 折線的轉折點
    private int[] lowText = new int[15];


    Context contex;

   private String[] wind = new String[15];

    private int min , max;

    private String[] time = new String[15];

    private String[] date = new String[15];

    private String[] textDay = new String[15];
    private int[] codeDay = new int[15];

    private String[] textNight = new String[15];
    private int[] codeNight = new int[15];

    private int[] highTemperature = new int[15];
    private int[] lowTemperature = new int[15];

    private String[] windDirection = new String[15];

    private int[] windScale = new int[15];


    private Bitmap mBitmap;
    // 座標軸底部的星期數

    private int[] datyImageId = new int[]{R.mipmap.ic_coollife_sunny_big,R.mipmap.ic_coollife_cloudy_big,
            R.mipmap.ic_coollife_overcast_big,R.mipmap.ic_coollife_shower_big,R.mipmap.ic_coollife_thundeshower_big,R.mipmap.ic_coollife_thundeshowehail_big ,R.mipmap.ic_coollife_lightrain_big,R.mipmap.ic_coollife_moderraterain_big,R.mipmap.ic_coollife_heavyrain_big
            ,R.mipmap.ic_coollife_rainsnow_big,R.mipmap.ic_coollife_snow_big,R.mipmap.ic_coollife_heavysnow_big};

    private int[] nightImageId = new int[]{R.mipmap.ic_coollife_nightsunny_big,R.mipmap.ic_coollife_nightcloudy_big,
            R.mipmap.ic_coollife_overcast_big,R.mipmap.ic_coollife_nightrain_big,R.mipmap.ic_coollife_thundeshower_big,R.mipmap.ic_coollife_thundeshowehail_big ,R.mipmap.ic_coollife_lightrain_big,R.mipmap.ic_coollife_moderraterain_big,R.mipmap.ic_coollife_heavyrain_big
            ,R.mipmap.ic_coollife_rainsnow_big,R.mipmap.ic_coollife_snow_big,R.mipmap.ic_coollife_heavysnow_big};
    private String[] str = new String[]{"1","2","3","4","5","6","7","8","9","10"};

    public FutureLineChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.contex = context;
        init();
    }

    public FutureLineChartView(Context context) {
        super(context);
        this.contex = context;
        init();
    }

    private void init(){
        ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        //步驟2:獲取ConnectivityManager對象對應的NetworkInfo對象
        //NetworkInfo對象包含網絡連接的所有信息
        //步驟3:根據需要取出網絡連接信息
        //獲取WIFI連接的信息
        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        Boolean isWifiConn = networkInfo.isConnected();

        //獲取移動數據連接的信息
        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        Boolean isMobileConn = networkInfo.isConnected();
        if(isWifiConn || isMobileConn)
            ininfuturedata();

        initTemperature();
        initTime();
        initWind();
        initdate();
        ani = new HistogramAnimation();
        ani.setDuration(0);
        titlePaint = new Paint();
    }

    private void ininfuturedata(){
        TPWeatherManager weatherManager;
        weatherManager = TPWeatherManager.sharedWeatherManager();
        weatherManager.initWithKeyAndUserId("rvjntsfqkzcsrtgd","U68230D6EE");
        weatherManager.getWeatherDailyArray(new TPCity(MyFragment.getName()),TPWeatherManager.TPWeatherReportLanguage.kSimplifiedChinese,
                TPWeatherManager.TPTemperatureUnit.kCelsius, new Date(), 15,
                new TPListeners.TPWeatherDailyListener() {
                    @Override
                    public void onTPWeatherDailyAvailable(TPWeatherDaily[] tpWeatherDailies, String s) {
                        if (tpWeatherDailies != null) {
                            for (int i = 0; i < tpWeatherDailies.length; i++) {
                                if(i == 0){
                                    textDay[i] = tpWeatherDailies[i].textDay;
                                    codeDay[i] = new Integer(tpWeatherDailies[i].codeDay);
                                    textNight[i] = tpWeatherDailies[i].textNight;
                                    codeNight[i] = new Integer(tpWeatherDailies[i].codeDay);

                                    highTemperature[i] = tpWeatherDailies[i].highTemperature;
                                    lowTemperature[i] = tpWeatherDailies[i].lowTemperature ;
                                    windDirection[i] = tpWeatherDailies[i].windDirection;
                                    windScale[i] = (int)tpWeatherDailies[i].windScale;
                                }
                                if(i == 1){
                                    textDay[i] = tpWeatherDailies[i].textDay;
                                    codeDay[i] = new Integer(tpWeatherDailies[i].codeDay);
                                    textNight[i] = tpWeatherDailies[i].textNight;
                                    codeNight[i] = new Integer(tpWeatherDailies[i].codeDay);

                                    highTemperature[i] = tpWeatherDailies[i].highTemperature;
                                    lowTemperature[i] = tpWeatherDailies[i].lowTemperature ;
                                    windDirection[i] = tpWeatherDailies[i].windDirection;
                                    windScale[i] = (int)tpWeatherDailies[i].windScale;
                                }
                                if (i ==2){
                                    textDay[i] = tpWeatherDailies[i].textDay;
                                    codeDay[i] = new Integer(tpWeatherDailies[i].codeDay);
                                    textNight[i] = tpWeatherDailies[i].textNight;
                                    codeNight[i] = new Integer(tpWeatherDailies[i].codeDay);

                                    highTemperature[i] = tpWeatherDailies[i].highTemperature;
                                    lowTemperature[i] = tpWeatherDailies[i].lowTemperature ;

                                    windDirection[i] = tpWeatherDailies[i].windDirection;
                                    windScale[i] = (int)tpWeatherDailies[i].windScale;
                                }
                            }
                        }
                        for(int i = 3; i < 15; i++){
                            textDay[i] = textDay[2];
                            codeDay[i] = codeDay[2];
                            textNight[i] = textNight[2];
                            codeNight[i] = codeNight[2];
                            highTemperature[i] = highTemperature[2];
                            lowTemperature[i] = lowTemperature[2];
                            windDirection[i] = windDirection[2];
                            windScale[i] = windScale[2];
                        }
                        initTemperature();
                        initWind();
                        addData = true;
                        startAnimation(ani);
                    }
                });
    }

    private void initdate(){
        String[] week = new String[]{"星期天","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int index = cal.get(Calendar.DAY_OF_WEEK);
        date[0] = "今天";
        for(int i = 1; i < 15;i++){
            date[i] = week[((index + i -1) % 7)];
        }
    }


    private void initWind(){
        if(windScale == null) {
            for (int i = 0; i < 15; i++)
                wind[i] = 1 + "級";
        }else {
            for (int i = 0; i < 15; i++)
                wind[i] = windScale[i] + "級";
        }
    }
    public void initTime(){
        Date d2 = new Date();
        long l1 = d2.getTime();
        for(int i = 0; i < 15; i++){
            l1 = l1 + 1000 * 60 * 60 * 24;
            Date d = new Date(l1);
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
            String sd = sdf.format(d);
            time[i] = sd;
        }
    }

    public void initTemperature(){
        max = highTemperature[0];
        for(int i = 0; i < highTemperature.length ; i++){
            if(highTemperature[i] > max){
                max = highTemperature[i];
            }
            if(highTemperature[i] < min){
                min = highTemperature[i];
            }
        }
        max = max + 5;
        for (int i =0; i < highTemperature.length;i++){
            hightText [i] =  max - highTemperature[i]  ;
        }

        min = lowTemperature[0];
        for(int i = 0 ;i < lowTemperature.length; i++){
            if(lowTemperature[i] > min){
                min = lowTemperature[i];
            }
        }
        min = min + 5;
        for (int i =0; i < lowTemperature.length;i++){
            lowText [i] =  min - lowTemperature[i]  ;
        }


    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        linePaint = new Paint();

        titlePaint.setAntiAlias(true);
        Rect bundle2 = new Rect();

        int perWidth = 2000 / 24;
        int hPerHeight = getHeight() / 60;

        //畫圖片
        Drawable drawable;

        Path path = new Path();
        mBitmap = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
        Canvas mCancas = new Canvas(mBitmap);

        //畫縱座標
        for (int i = 1 ; i <= str.length   ; i++){
            titlePaint.setTextSize(sp2px(13));
            titlePaint.setColor(Color.WHITE);
            titlePaint.getTextBounds(str[i - 1],0,str[(i - 1)].length(),bundle2);
        }
        for (int i = 0; i< 15; i++){
            y = i * hPerHeight;
            //初始位置x 間隔
            x = i * (perWidth + 30) + dp2px(30);

            //畫折線
            if (i == 0) {
                path.moveTo(x, hightText[i] * hPerHeight  + 260);
            } else {
                path.lineTo(x, hightText[i] * hPerHeight + 260);
            }
            linePaint.setColor(Color.parseColor("#bb2222"));
            linePaint.setAntiAlias(true);

            paint = new Paint();
            paint.setColor(Color.YELLOW);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(dp2px(1));

            mCancas.drawText(date[i],x - 40, 50,titlePaint);
            mCancas.drawText(time[i],x - 40, 100,titlePaint);

            drawable = contex.getResources().getDrawable(R.mipmap.btn_warn_alert_yellow);
            drawable.setBounds(x -40,130,x + 40,170);
            drawable.draw(canvas);

            mCancas.drawText("良好",x - 30, 160,titlePaint);

            //畫點
            mCancas.drawCircle(x, hightText[i] * hPerHeight  + 260, dp2px(3), linePaint);
            mCancas.drawText(max - hightText[i] + "°",x - 20, hightText[i] * hPerHeight + 240,titlePaint);

            if(addData) {
                drawable = contex.getResources().getDrawable(datyImageId[selectindex(codeDay[i])]);
                drawable.setBounds(x -40,220,x + 20,280);
                drawable.draw(canvas);

                drawable = contex.getResources().getDrawable(nightImageId[selectindex(codeNight[i])]);
                drawable.setBounds(x -40,520,x +20,580);
                drawable.draw(canvas);

                mCancas.drawText(textDay[i], x - 40, 210, titlePaint);

                mCancas.drawText(textNight[i], x - 40, 640, titlePaint);

                mCancas.drawText(windDirection[i],x - 40, 700,titlePaint);
            }else {
                drawable = contex.getResources().getDrawable(R.mipmap.ic_coollife_sunny_big);
                drawable.setBounds(x -40,220,x + 20,280);
                drawable.draw(canvas);

                drawable = contex.getResources().getDrawable(R.mipmap.ic_coollife_nightsunny_big);
                drawable.setBounds(x -40,520,x +20,580);
                drawable.draw(canvas);

                mCancas.drawText( "  晴  ", x - 40, 210, titlePaint);

                mCancas.drawText("  晴  ", x - 40, 640, titlePaint);

                mCancas.drawText("西北風",x - 40, 700,titlePaint);
            }


            mCancas.drawText(wind[i],x - 40, 760,titlePaint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
            mCancas.drawPath(path, paint);
        }

        for (int i = 0; i< 15; i++){
            y = i * hPerHeight;
            //初始位置x 間隔
            x = i * (perWidth + 30) + dp2px(30);

            //畫折線
            if (i == 0) {
                path.moveTo(x, lowText[i] * hPerHeight  + 360);
            } else {
                path.lineTo(x, lowText[i] * hPerHeight + 360);
            }

            linePaint.setColor(Color.parseColor("#bb2222"));
            linePaint.setAntiAlias(true);

            paint = new Paint();
            paint.setColor(Color.BLUE);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(dp2px(1));

            //畫點
            mCancas.drawCircle(x, lowText[i] * hPerHeight  + 360, dp2px(3), linePaint);

            mCancas.drawText(min - lowText[i]  + "°",x - 0, lowText[i] * hPerHeight + 400,titlePaint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
            mCancas.drawPath(path, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
        paint.setStyle(Paint.Style.FILL);

        mCancas.drawRect(preX + dp2px(30), 0, getWidth(), getHeight(), paint);
        canvas.drawBitmap(mBitmap, 0, 0, null);
    }

    private int selectindex(int i){
        if(i < 4){
            return 0;
        }else if(i < 8){
            return 1;
        }else if( i == 9){
            return 2;
        }else if(i == 10){
            return 3;
        }else if(i == 11){
            return 4;
        }else if(i == 12){
            return 5;
        }else if(i == 13){
            return 6;
        }else if(i == 14){
            return 7;
        }else if(i < 20){
            return 8;
        }else if(i == 20){
            return 9;
        }else if(i < 23){
            return 10;
        }else if(i < 26){
            return 11;
        }
        return 0;
    }

    private int dp2px(int value){
        float v = getContext().getResources().getDisplayMetrics().density;
        return (int)(v * value + 0.5f);
    }

    private int sp2px(int value){
        float v = getContext().getResources().getDisplayMetrics().scaledDensity;
        return (int)(v * value + 0.5f);
    }

    private class HistogramAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if(interpolatedTime < 1.0f ){
                preX = (int)((getWidth() - dp2px(30)) * interpolatedTime);
            }else {
                preX = getWidth();
            }
            invalidate();
        }
    }
    public void start() {
        startAnimation(ani);
    }
}

8建立MyFragment碎片

public class MyFragment extends Fragment {

    TextView updata_time;
    TextView temperature ;
    TextView weather_case ;
    TextView wind ;

    TextView today_air_index ;
    ImageView today_cloud_iv ;
    TextView today_temperature;
    TextView today_cloud_tv ;

    TextView tomorrow_air_index ;
    ImageView tomorrow_cloud_iv ;
    TextView tomorrow_temperature ;
    TextView tomorrow_cloud_tv ;

    TextView title;

    private View view;

    private static String name;

    private ActivityManager am;

    private LineChartView lineChartView;

    private FutureLineChartView futureLineChartView;

    private static TPWeatherManager weatherManager;

    private static TPCity cityName;

    private static TPWeatherManager.TPWeatherReportLanguage language;

    private static TPWeatherManager.TPTemperatureUnit unit;

    private int[] imageId = new int[]{R.mipmap.ic_coollife_sunny_big,R.mipmap.ic_coollife_cloudy_big,
    R.mipmap.ic_coollife_overcast_big,R.mipmap.ic_coollife_shower_big,R.mipmap.ic_coollife_thundeshower_big,R.mipmap.ic_coollife_thundeshowehail_big ,R.mipmap.ic_coollife_lightrain_big,R.mipmap.ic_coollife_moderraterain_big,R.mipmap.ic_coollife_heavyrain_big
    ,R.mipmap.ic_coollife_rainsnow_big,R.mipmap.ic_coollife_snow_big,R.mipmap.ic_coollife_heavysnow_big};

    public static void setName(String sname) {
        name = sname;
    }

    public static String getName() {
        return name;
    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment,container,false);

        am = ActivityManager.getInstance();
        ImageView add = (ImageView)view.findViewById(R.id.top_iv_add);
        title = (TextView)view.findViewById(R.id.top_tv_title);
        ImageView copy = (ImageView)view.findViewById(R.id.top_iv_copy);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //添加城市
                Intent intent = new Intent(getContext(),AddCityActivity.class);
                startActivity(intent);
            }
        });
        title.setText(name);

        initView(view);

        weatherManager = TPWeatherManager.sharedWeatherManager();
        weatherManager.initWithKeyAndUserId("rvjntsfqkzcsrtgd","U68230D6EE");
        cityName = new TPCity(name);
        language = TPWeatherManager.TPWeatherReportLanguage.kSimplifiedChinese;
        unit = TPWeatherManager.TPTemperatureUnit.kCelsius;


        //步驟1:通過Context.getSystemService(Context.CONNECTIVITY_SERVICE)獲得ConnectivityManager對象
        ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        //步驟2:獲取ConnectivityManager對象對應的NetworkInfo對象
        //NetworkInfo對象包含網絡連接的所有信息
        //步驟3:根據需要取出網絡連接信息
        //獲取WIFI連接的信息
        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        Boolean isWifiConn = networkInfo.isConnected();

        //獲取移動數據連接的信息
        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        Boolean isMobileConn = networkInfo.isConnected();

        if(isWifiConn || isMobileConn)
            initData();
        else Toast.makeText(getContext(),"請打開網絡!重新啓動應用",Toast.LENGTH_SHORT).show();

        lineChartView = (LineChartView)view.findViewById(R.id.line_chart);
        futureLineChartView = (FutureLineChartView)view.findViewById(R.id.future_line_chart);
        copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //TODO 截屏
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                String time = sdf.format(date);
                String filePath =  Environment.getExternalStorageDirectory() + "/DCIM/Screenshots/"
                      + time + "jp.png";
                ScreenShot.shoot( getActivity(),new File(filePath));
                //保存圖片
                Toast.makeText(getActivity(),"截屏完成!",Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
    public void initView(View view){
        updata_time = (TextView) view.findViewById(R.id.tv_update_time);
        temperature = (TextView) view.findViewById(R.id.tv_temperature);
        weather_case = (TextView) view.findViewById(R.id.tv_weather_case);
        wind = (TextView) view.findViewById(R.id.tv_wind);


        today_air_index = (TextView) view.findViewById(R.id.tv_air_index);
        today_cloud_iv = (ImageView) view.findViewById(R.id.iv_cloud);
        today_temperature = (TextView) view.findViewById(R.id.tv_today_temperature);
        today_cloud_tv = (TextView) view.findViewById(R.id.tv_today_cloud);


        tomorrow_air_index = (TextView) view.findViewById(R.id.tv_tomorrow_air_index);
        tomorrow_cloud_iv = (ImageView) view.findViewById(R.id.iv_tomorrow_cloud);
        tomorrow_temperature = (TextView) view.findViewById(R.id.tv_tomorrow_temperature);
        tomorrow_cloud_tv = (TextView) view.findViewById(R.id.tv_tomorrow_cloud);


        //TODO 待完善
    }

    public void initData(){
        weatherManager.getWeatherNow(cityName,language,
                unit , new TPListeners.TPWeatherNowListener() {
                    @Override
                    public void onTPWeatherNowAvailable(TPWeatherNow tpWeatherNow, String s) {
                        if(tpWeatherNow != null){
                            weather_case.setText(tpWeatherNow.text + "");
                            Log.d("debug1","tpWeatherNow.text : " + tpWeatherNow.text);
                            temperature.setText(tpWeatherNow.temperature + "°");
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            updata_time.setText(sdf.format(tpWeatherNow.lastUpdateDate) + " 發佈");
                            /*
                            Log.d("debug1","天氣現象文字,例如“多雲” " + tpWeatherNow.text);
                            Log.d("debug1","天氣現象代碼,例如“4”  " + tpWeatherNow.code);
                            Log.d("debug1"," 溫度,單位爲c攝氏度或f華氏度 " + tpWeatherNow.temperature );
                            Log.d("debug1"," 體感溫度,單位爲c攝氏度或f華氏度 " + tpWeatherNow.feelsLikeTemperature );
                            Log.d("debug1","風向角度,範圍0~360,0爲正北,90爲正東,180爲正南,270爲正西 " + tpWeatherNow.windDirectionDegree);
                            Log.d("debug1","雲量,範圍0~100,天空被雲覆蓋的百分比 " + tpWeatherNow.clouds);
                            Log.d("debug1","數據更新時間(該城市的本地時間) " + tpWeatherNow.lastUpdateDate);
                            */
                        }else {
                            Log.d("debug1","錯誤");
                        }
                    }
                });
        weatherManager.getWeatherDailyArray(cityName,language,unit,
                new Date(), 15, new TPListeners.TPWeatherDailyListener() {
                    @Override
                    public void onTPWeatherDailyAvailable(TPWeatherDaily[] tpWeatherDailies, String s) {
                        if (tpWeatherDailies != null) {
                            for (int i = 0; i < tpWeatherDailies.length; i++) {
                                if(i == 0){
                                    String sWind = String.valueOf((int) tpWeatherDailies[i].windScale);
                                    sWind = sWind + "級";
                                    wind.setText(sWind);
                                    if(tpWeatherDailies[i].textDay.equals(tpWeatherDailies[i].textNight))
                                        today_cloud_tv.setText("        " + tpWeatherDailies[i].textDay);
                                    else
                                        today_cloud_tv.setText(tpWeatherDailies[i].textDay + "轉" + tpWeatherDailies[i].textNight);
                                    String sTemperature = tpWeatherDailies[i].lowTemperature +"~";
                                    sTemperature = sTemperature + tpWeatherDailies[i].highTemperature ;
                                    sTemperature = sTemperature + "℃";
                                    today_temperature.setText(sTemperature);
                                    String codeDay = tpWeatherDailies[i].codeDay;
                                    int index = new Integer(codeDay);
                                    today_cloud_iv.setImageResource(imageId[selectindex(index)]);

                                }
                                if(i == 1){
                                    if(tpWeatherDailies[i].textDay.equals(tpWeatherDailies[i].textNight))
                                        today_cloud_tv.setText("    " + tpWeatherDailies[i].textDay);
                                    else
                                        tomorrow_cloud_tv.setText(tpWeatherDailies[i].textDay + "轉" + tpWeatherDailies[i].textNight);
                                    String sTemperature = tpWeatherDailies[i].lowTemperature +"~";
                                    sTemperature = sTemperature + tpWeatherDailies[i].highTemperature ;
                                    sTemperature = sTemperature + "℃";
                                    tomorrow_temperature.setText(sTemperature);
                                    String codeDay = tpWeatherDailies[i].codeDay;
                                    int index = new Integer(codeDay);
                                    tomorrow_cloud_iv.setImageResource(imageId[selectindex(index)]);
                                }
                                /*Log.d("debug1", "日期 " + tpWeatherDailies[i].date);
                                Log.d("debug1", "白天天氣現象文字 " + tpWeatherDailies[i].textDay);
                                Log.d("debug1", "白天天氣現象代碼 " + tpWeatherDailies[i].codeDay);
                                Log.d("debug1", "晚間天氣現象文字 " + tpWeatherDailies[i].textNight);
                                Log.d("debug1", "晚間天氣現象代碼 " + tpWeatherDailies[i].codeNight);
                                Log.d("debug1", "當天最高溫度 " + tpWeatherDailies[i].highTemperature);
                                Log.d("debug1", "當天最低溫度 " + tpWeatherDailies[i].lowTemperature);
                                Log.d("debug1", "降水概率,範圍0~100,單位百分比 " + tpWeatherDailies[i].chanceOfRain);
                                Log.d("debug1", "風向文字 " + tpWeatherDailies[i].windDirection);
                                Log.d("debug1", "風向角度,範圍0~360 " + tpWeatherDailies[i].windDirectionDegree);
                                Log.d("debug1", "風速,單位km/h(當unit=c時)、mph(當unit=f時) " + tpWeatherDailies[i].windSpeed);
                                Log.d("debug1", "風力等級 " + tpWeatherDailies[i].windScale);
                                */
                            }
                        }
                    }
                });
    }
    //將獲取到的天氣現象數字轉換爲圖片索引
    private int selectindex(int i){
        if(i < 4){
            return 0;
        }else if(i < 8){
            return 1;
        }else if( i == 9){
            return 2;
        }else if(i == 10){
            return 3;
        }else if(i == 11){
            return 4;
        }else if(i == 12){
            return 5;
        }else if(i == 13){
            return 6;
        }else if(i == 14){
            return 7;
        }else if(i < 20){
            return 8;
        }else if(i == 20){
            return 9;
        }else if(i < 23){
            return 10;
        }else if(i < 26){
            return 11;
        }
        return 0;
    }

    public void onResume() {
        super.onResume();
        lineChartView.start();
        futureLineChartView.start();
    }
}

9建立ActivityManager管理activity

public class ActivityManager {

   Activity activity;

    public boolean firstOpen = true;

    private List<String> mList = new ArrayList<>();

    private static ActivityManager instance;

    private List<Activity> list;
    //默認鈴聲的地址

    public List<String> getmList() {
        return mList;
    }

    public void setmList(List<String> list){
        mList = list;
    }

    public void removemList(String name){
        mList.remove(name);
    }

    public boolean addList(String name) {
        for (String n:mList) {
            if("-1".equals(name))
                return false;
            if(n.equals(name))
                return false;
        }
        mList.add(name);
        return true;
    }

    public static ActivityManager getInstance() {
        if (instance == null){
            instance = new ActivityManager();
        }
        return instance;
    }

    //添加Activity進列表
    public void addActivity(Activity av) {
        //如果列表爲空則新建列表
        if(list==null)
            list=new ArrayList<Activity>();
        if (av != null) {
            if(list.contains(av))
                list.remove(av);
            list.add(av);
        }
    }

    //退出所有程序
    public void exitAllProgress() {
        for (int i = 0; i < list.size(); i++) {
            Activity av = list.get(i);
            av.finish();
        }
    }


}

10建立ScreenShot實現截屏與保存

public class ScreenShot {

    public static void shoot(Activity a,File filePath){
        if(filePath == null){
            return;
        }
        if(!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            if(fos != null){
                takeScreenShot(a).compress(Bitmap.CompressFormat.PNG,100,fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(fos != null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static Bitmap takeScreenShot(Activity activity){
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        Rect fram = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(fram);
        int statusBarHeight = fram.top;
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();
        Bitmap b = Bitmap.createBitmap(bitmap,0,statusBarHeight,width,height - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }

}

11建立AddCityActivity實現添加城市和顯示已添加城市

public class AddCityActivity extends Activity {

    private List<String> dataList;

    private ActivityManager am;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_city);
        super.onCreate(savedInstanceState);
        am = ActivityManager.getInstance();
        am.addActivity(this);
        final EditText city_name = (EditText)findViewById(R.id.et_city_name);
        Button add_city = (Button)findViewById(R.id.btn_add_city);
        add_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!"".equals(city_name.getText().toString())) {
                    OpenActivity(city_name.getText().toString());
                }else {
                    Toast.makeText(getApplicationContext(),"添加城市不能爲空",Toast.LENGTH_SHORT).show();
                }
            }
        });
        dataList = new ArrayList<>();
        List<String> list = am.getmList();
        for (String s:list){
            dataList.add(s);
        }
        ListView myCityList = (ListView) findViewById(R.id.add_lv_listView);
        myCityList.setAdapter(new MyAdapt());
        ImageView back = (ImageView)findViewById(R.id.iv_add_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OpenActivity("-1");
            }
        });
    }
    class MyAdapt extends BaseAdapter{

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int i) {
            return dataList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            View v;
            if(view == null){
                v = View.inflate(viewGroup.getContext(),R.layout.add_city_item,null);
            }else v = view;
            TextView tv_number = (TextView) v.findViewById(R.id.add_item_tv_name);
            tv_number.setText(dataList.get(i));
            v.findViewById(R.id.add_item_iv_delect).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    am.removemList(dataList.get(i));
                    dataList.remove(i);
                    notifyDataSetChanged();
                }
            });

            return v;
        }
    }

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.city11:
                OpenActivity("北京");
                break;
            case R.id.city12:
                OpenActivity("上海");
                break;
            case R.id.city13:
                OpenActivity("廣州");
                break;
            case R.id.city21:
                OpenActivity("深圳");
                break;
            case R.id.city22:
                OpenActivity("武漢");
                break;
            case R.id.city23:
                OpenActivity("南京");
                break;
            case R.id.city31:
                OpenActivity("杭州");
                break;
            case R.id.city32:
                OpenActivity("西安");
                break;
            case R.id.city33:
                OpenActivity("鄭州");
                break;
            case R.id.city41:
                OpenActivity("成都");
                break;
            case R.id.city42:
                OpenActivity("東莞");
                break;
            case R.id.city43:
                OpenActivity("瀋陽");
                break;
        }
    }
    private void OpenActivity(String cityName){
        Intent intent = new Intent(AddCityActivity.this,MainActivity.class);
        intent.putExtra("county_name",cityName);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            OpenActivity("-1");
        }
        return super.onKeyDown(keyCode, event);
    }
}

12MainActivity實現初始化和調用

public class MainActivity extends FragmentActivity {

    private ViewPager pager;

    private List<MyFragment> mList = new ArrayList<>();

    private FragmentPagerAdapter adapter;

    private ActivityManager am;

    private int curIndex = 0;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        am = ActivityManager.getInstance();
        am.addActivity(this);



        //數據讀取
        if (am.firstOpen){
            File file = new File(getApplicationContext().getFilesDir().getPath(),"Config.txt");
            try {
                BufferedReader bf = new BufferedReader(new FileReader(file));
                String s;
                while ((s =  bf.readLine()) != null){
                    am.addList(s);
                }
                bf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            am.firstOpen = false;
        }

        Intent intent = getIntent();
        String title_name = intent.getStringExtra("county_name");

        setOverflowShowingAlways();
        initMyList();
        if(title_name != null && am.addList(title_name)){
            MyFragment myFragment = new MyFragment();
            myFragment.setName(title_name);
            mList.add(myFragment);
        }
        initView();
    }

    private void initMyList(){
        if (am.getmList().size() != 0){
            for (String name : am.getmList()) {
                MyFragment myfragment = new MyFragment();
                myfragment.setName(name);
                mList.add(myfragment);
            }
        }else {
            MyFragment myFragment = new MyFragment();
            myFragment.setName("咸陽");
            mList.add(myFragment);
            am.addList("咸陽");
        }
    }

    private void initView(){
        pager = (ViewPager)findViewById(R.id.vp_pager);
        adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setOnPageChangeListener(new MyOnPageChangeListener());

    }
    protected void setOverflowShowingAlways(){
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.
                    getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config,false);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener{

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if(curIndex != position)
                MyFragment.setName(am.getmList().get(position));
        }

        @Override
        public void onPageSelected(int position) {
            //TODO 加載數據
            curIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }

    }

    private long firstTime=0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                File file = new File(getApplicationContext().getFilesDir().getPath(),"Config.txt");
                try {
                    PrintStream ps = new PrintStream(new FileOutputStream(file));
                    for(String s:am.getmList()){
                        ps.println(s);
                    }
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                am.exitAllProgress();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }

}

13在AndroidManifest.xml添加所需權限

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.GET_TASKS" />
  ...
  <activity android:name=".activity.AddCityActivity"/>

源碼下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章