Flutter开源项目——Android免费壁纸应用

简介

free_wallpaper是一款基于flutter的免费Android壁纸应用

项目明细

开发环境:
android studio 3.5
Flutter 1.12.13+hotfix.7 • channel stable
Framework • revision 9f5ff2306b
Engine • revision a67792536c
Tools • Dart 2.7.0

主要功能

1.分端浏览
2.筛选功能
3.搜索功能
4.搜索历史记录
5.下载壁纸和设置壁纸
6.下载管理
(更多功能还在陆续填坑中...)

项目特点

本项目采用Serverless模式,使用dio网络请求库和jsoup获取数据。使用百度图片接口实现搜索功能;使用CachedNetworkImage加载网络图片;使用Android插件的形式实现了部分Android原生功能,如设置壁纸和更新MediaStore等。

部分代码

1.WallpaperPlugin(修改自wallpaper插件,解决了dio库版本不兼容的问题,添加了设置本地图片的功能)

import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.app.WallpaperManager
import android.content.ActivityNotFoundException
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import io.flutter.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.io.File
import java.io.IOException


/** WallpaperPlugin  */
class WallpaperPlugin constructor(var mContext: Context): FlutterActivity(), FlutterPlugin, MethodCallHandler {
    private var id = 0
    private var res = ""
    private var channel: MethodChannel?=null


    @TargetApi(Build.VERSION_CODES.FROYO)
    private fun setWallpaper(i: Int, imagePath: String): String {
        id = i
        val wallpaperManager = WallpaperManager.getInstance(mContext)
        val file = File(imagePath)
        // set bitmap to wallpaper
        val bitmap = BitmapFactory.decodeFile(file.absolutePath)
        if (id == 1) {
            try {
                res = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_SYSTEM)
                    "Home Screen Set Successfully"
                } else {
                    "To Set Home Screen Requires Api Level 24"
                }
            } catch (ex: IOException) {
                ex.printStackTrace()
            }
        } else if (id == 2) try {
            res = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)
                "Lock Screen Set Successfully"
            } else {
                "To Set Lock Screen Requires Api Level 24"
            }
        } catch (e: IOException) {
            res = e.toString()
            e.printStackTrace()
        } else if (id == 3) {
            try {
                wallpaperManager.setBitmap(bitmap)
                res = "Home And Lock Screen Set Successfully"
            } catch (e: IOException) {
                res = e.toString()
                e.printStackTrace()
            }
        } else if (id == 4) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED &&
                        activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    activity.requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
                } else {
                    Uri.fromFile(file)
                    val contentURI = getImageContentUri(this, file)
                    val intent = Intent(wallpaperManager.getCropAndSetWallpaperIntent(contentURI))
                    val mime = "image/*"
                    intent.setDataAndType(contentURI, mime)
                    try {
                        startActivityForResult(intent, 2)
                    } catch (e: ActivityNotFoundException) { //handle error
                        res = "Error To Set Wallpaer"
                    }
                }
            }
        }
        return res
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        Log.d("Tag", "resultcode=" + resultCode + "requestcode=" + requestCode)
        res = when (resultCode) {
            Activity.RESULT_OK -> {
                "System Screen Set Successfully"
            }
            Activity.RESULT_CANCELED -> {
                "setting Wallpaper Cancelled"
            }
            else -> {
                "Something Went Wrong"
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }




    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "getPlatformVersion" -> result.success("" + Build.VERSION.RELEASE)
            "HomeScreen" -> result.success(setWallpaper(1, call.arguments as String))
            "LockScreen" -> result.success(setWallpaper(2, call.arguments as String))
            "Both" -> result.success(setWallpaper(3, call.arguments as String))
            "SystemWallpaer" -> result.success(setWallpaper(4, call.arguments as String))
            else -> result.notImplemented()
        }
    }


    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(binding.binaryMessenger, "WallpaperPlugin")
        channel!!.setMethodCallHandler(WallpaperPlugin(mContext))

    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel!!.setMethodCallHandler(null)
        channel=null
    }

    companion object {

        fun getImageContentUri(context: Context, imageFile: File): Uri? {
            val filePath = imageFile.absolutePath
            Log.d("Tag", filePath)
            val cursor = context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.Media._ID),
                    MediaStore.Images.Media.DATA + "=? ", arrayOf(filePath), null)
            return if (cursor != null && cursor.moveToFirst()) {
                val id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.MediaColumns._ID))
                val baseUri = Uri.parse("content://media/external/images/media")
                Uri.withAppendedPath(baseUri, "" + id)
            } else {
                if (imageFile.exists()) {
                    val values = ContentValues()
                    values.put(MediaStore.Images.Media.DATA, filePath)
                    context.contentResolver.insert(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                } else {
                    null
                }
            }
        }
    }

}

2.MediaStorePlugin(更新本机媒体库)

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File


/**
 * description:
 * author:luoxingyuan
 */
class MediaStorePlugin constructor(var mContext: Context) : FlutterPlugin, MethodChannel.MethodCallHandler {
    private var channel: MethodChannel?=null
    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(binding.binaryMessenger, "MediaStorePlugin")
        channel!!.setMethodCallHandler(MediaStorePlugin(mContext))
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel!!.setMethodCallHandler(null)
        channel=null
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "refreshMediaStore" -> result.success(sendMediaBroadcast(call.arguments as String))
            else -> result.notImplemented()
        }
    }

    private fun sendMediaBroadcast(filePath: String) {
        val file = File(filePath)
        //通知相册更新
        MediaStore.Images.Media.insertImage(mContext.contentResolver, BitmapFactory.decodeFile(file.absolutePath), file.name, null)
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri: Uri = Uri.fromFile(file)
        intent.data = uri
        mContext.sendBroadcast(intent)
    }

}

3.PC端壁纸分类列表

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:free_wallpaper/model/category_model.dart';
import 'package:free_wallpaper/net/address.dart';
import 'package:free_wallpaper/net/http_callback.dart';
import 'package:free_wallpaper/net/http_manager.dart';
import 'package:free_wallpaper/net/result_data.dart';
import 'package:free_wallpaper/utils/toast.dart';
import 'package:free_wallpaper/widget/error_placeholder.dart';
import 'package:free_wallpaper/widget/loading_dialog.dart';
import 'package:html/parser.dart' show parse;

import 'page_albums.dart';
/*
  description:
  author:59432
  create_time:2020/1/22 12:59
*/

class CategoriesPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => CategoriesPageState();
}

class CategoriesPageState extends State<CategoriesPage> {
  var categories = List<CategoryModel>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _requestData(showLoading: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:  RefreshIndicator(
          color: Colors.pinkAccent,
          backgroundColor: Colors.white,
          child: Container(
            margin: const EdgeInsets.only(left: 8.0, right: 8, top: 8),
            child: GridView.count(
              // Create a grid with 2 columns. If you change the scrollDirection to
              // horizontal, this produces 2 rows.
              crossAxisCount: 3,
              crossAxisSpacing: 8.0,
              mainAxisSpacing: 8,
              // Generate 100 widgets that display their index in the List.
              children: List.generate(categories.length, (index) {
                return _buildItem(context, categories[index]);
              }),
            ),
          ), onRefresh: _refreshData),
    );
  }

  _requestData({showLoading = false}) {
    HttpManager.getInstance(baseUrl: Address.MEI_ZHUO)
        .getHtml("/zt/index.html", HttpCallback(
        onStart: () {
          if (showLoading) {
            LoadingDialog.showProgress(context);
          }
        },
        onSuccess: (ResultData data) {
          if (showLoading) {
            LoadingDialog.dismiss(context);
          }
          var doc = parse(data.data);
          var aTags = doc.body
              .getElementsByClassName("nr_zt w1180")
              .first
              .getElementsByTagName("a");
          categories.clear();
          aTags.forEach((a) {
            var href = a.attributes["href"];
            var src = a
                .querySelector("img")
                .attributes["src"];
            var category = a
                .querySelector("p")
                .text;
            categories.add(CategoryModel(name: category, href: href, src: src));
          });

          setState(() {

          });
        },
        onError: (ResultData error) {
          if (showLoading) {
            LoadingDialog.dismiss(context);
          }
          ToastUtil.showToast(error.data);
        }
    ));
  }

  Widget _buildItem(BuildContext context, CategoryModel category) {
    return  GestureDetector(
      onTap: () => _onItemClick(category),
      child: ClipOval(
        child: Stack(
          alignment: const Alignment(0.0, 1.0),
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: category.src,
              placeholder: (context, url) => Center(child: CircularProgressIndicator()),
              errorWidget: (context, url, error) => ErrorPlaceHolder(),
              fit: BoxFit.fill,
              height: (MediaQuery
                  .of(context)
                  .size
                  .width) / 3,
            ),
            Container( //分析 4
              width: (MediaQuery
                  .of(context)
                  .size
                  .width) / 3,
              decoration:  BoxDecoration(
                color: Colors.black45,
              ),
              child: Text(
                category.name,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 16.0,
                  color: Colors.white,
                ),
              ),
            ),
          ],

        ),
      ),
    );
  }

  _onItemClick(CategoryModel category) {
    Navigator.push(
      context,
       MaterialPageRoute(builder: (context) =>  AlbumsPage(category, false)),
    );
  }

  Future<void> _refreshData() async {
    _requestData();
  }
}

预览

Screenshot_2020-02-11-18-09-59-827_wallpaper.cn.mewlxy.free_wallpaper.jpg
Screenshot_2020-02-11-18-10-13-965_wallpaper.cn.mewlxy.free_wallpaper.jpg
Screenshot_2020-02-11-18-11-12-049_wallpaper.cn.mewlxy.free_wallpaper.jpg
Screenshot_2020-02-11-18-11-48-216_wallpaper.cn.mewlxy.free_wallpaper.jpg

项目地址

https://github.com/lxygithub/free_wallpaper

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,686评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,668评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,160评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,736评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,847评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,043评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,129评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,872评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,318评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,645评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,777评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,861评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,589评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,687评论 2 351