添加项目文件。

This commit is contained in:
杨皓
2020-04-03 11:55:02 +08:00
parent f8a6829e30
commit d4e7a559f2
178 changed files with 20595 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
Any raw assets you want to be deployed with your application can be placed in
this directory (and child directories) and given a Build Action of "AndroidAsset".
These files will be deployed with your package and will be accessible using Android's
AssetManager, like this:
public class ReadAsset : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
InputStream input = Assets.Open ("my_asset.txt");
}
}
Additionally, some Android functions will automatically load asset files:
Typeface tf = Typeface.CreateFromAsset (Context.Assets, "fonts/samplefont.ttf");

View File

@@ -0,0 +1,71 @@
using Android.App;
using Android.Content;
using System;
namespace XXCpzs.Droid
{
[BroadcastReceiver]
/// <summary>
/// 下载通知接收器
/// </summary>
public class DownloadReceiver : BroadcastReceiver
{
public long downloadId = 0;
public DownloadReceiver()
{
}
public DownloadReceiver(long downloadId)
{
this.downloadId = downloadId;
}
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action == DownloadManager.ActionDownloadComplete)
{
#region
DownloadManager manager = (DownloadManager)context.GetSystemService(Context.DownloadService);
//获取下载id,默认值-1
var downId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1);
if (downId == downloadId)
{
Android.Database.ICursor cursor = null;
try
{
DownloadManager.Query query = new DownloadManager.Query();
query.SetFilterById(downId);
cursor = manager.InvokeQuery(query);
if (cursor.MoveToFirst())
{
//获取文件下载路径
var downloadedTo = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri));
//var apkUri = manager.GetUriForDownloadedFile(downId);//错误路径
var installIntent = new Intent(Intent.ActionView);
installIntent.SetDataAndType(Android.Net.Uri.Parse(downloadedTo), "application/vnd.android.package-archive");
//给目标程序读改uri的权限。
installIntent.AddFlags(ActivityFlags.NewTask);
if (Android.OS.Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M)
installIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
// installIntent.SetFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask);
context.StartActivity(installIntent);
}
if (cursor != null)
cursor.Close();
}
catch (Exception ex)
{
}
context.UnregisterReceiver(this);
}
#endregion
}
else if (intent.Action == DownloadManager.ActionNotificationClicked)
{
}
}
}
}

View File

@@ -0,0 +1,115 @@
using Android.App;
using Android.Content;
using Android.Widget;
using System;
namespace XXCpzs.Droid
{
public class FileDownload
{
#region ----
/// <summary>
/// 使用DownloadManager下载安装文件
/// </summary>
/// <param name="mContext"></param>
/// <param name="apkAddress"></param>
public static void DownloadUpdateFile(Context mContext, string apkAddress)
{
var apkFileName = System.IO.Path.GetFileName(apkAddress);
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(apkAddress));
// request.SetAllowedNetworkTypes(DownloadNetwork.Wifi);//网络环境
//request.SetDestinationInExternalPublicDir("download", "update1.apk");
request.SetDestinationInExternalFilesDir(mContext, Android.OS.Environment.DirectoryDownloads, apkFileName);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetMimeType("application/vnd.android.package-archive");
//设置通知信息
request.SetTitle(apkFileName);
request.SetDescription("软件更新");
//设置为可见和可管理
request.SetVisibleInDownloadsUi(true);
//设置为可被媒体扫描器找到
request.AllowScanningByMediaScanner();
request.SetAllowedOverRoaming(false);
//下载管理
DownloadManager downManager = (DownloadManager)mContext.GetSystemService(Context.DownloadService);
//获取此次下载的ID,返回一个唯一编号(用于识别通知来源)
var refrence = downManager.Enqueue(request);
// 注册广播监听系统的下载完成事件。
IntentFilter intentFilter = new IntentFilter(DownloadManager.ActionDownloadComplete);
var boradcastReceiver = new DownloadReceiver(refrence);
mContext.RegisterReceiver(boradcastReceiver, intentFilter);
/*备注:服务器端apk文件mime类型为application/vnd.android.package-archive
* 需要权限:android.permission.INTERNET和android.permission.WRITE_EXTERNAL_STORAGE
*/
}
/// <summary>
/// 自定义下载更新
/// </summary>
/// <param name="mContext"></param>
/// <param name="apkAddress"></param>
public void DownloadUpdateFile2(Context mContext, String apkAddress)
{
//权限检查
if (mContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
{
MainActivity.Instance.RequestPermissions(new string[] { Android.Manifest.Permission.WriteExternalStorage }, 1001);
return;
}
Java.IO.FileOutputStream outputStream = null;
System.IO.Stream inputStream = null;
Java.Net.HttpURLConnection connection = null;
Java.IO.File installFile = null;
try
{
var url = new Java.Net.URL(apkAddress);
connection = (Java.Net.HttpURLConnection)url.OpenConnection();
connection.ConnectTimeout = 60 * 1000;//1分钟
connection.ReadTimeout = 60 * 10 * 1000;
connection.Connect();
if (connection.ResponseCode != Java.Net.HttpStatus.Ok)
{
var errorMessage = connection.ResponseCode.ToString() + " " + connection.ResponseMessage;
return;
}
var contentLength = connection.ContentLength;
inputStream = connection.InputStream;
var downloadFile = Android.Net.Uri.FromFile(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads));
installFile = new Java.IO.File(downloadFile.Path, System.IO.Path.GetFileName(apkAddress));
outputStream = new Java.IO.FileOutputStream(installFile, false);//需要获取存储权限
byte[] data = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.Read(data, 0, data.Length)) > 0)
{
total += count;
outputStream.Write(data, 0, count);
}
}
catch (Exception ex)
{
Toast.MakeText(mContext, ex.Message, ToastLength.Long).Show();
}
if (outputStream != null)
outputStream.Close();
if (inputStream != null)
inputStream.Close();
if (connection != null)
connection.Disconnect();
if (installFile != null && installFile.Exists())
{
var installIntent = new Intent(Intent.ActionView);
installIntent.SetDataAndType(Android.Net.Uri.FromFile(installFile), "application/vnd.android.package-archive");
mContext.StartActivity(installIntent);
}
}
#endregion
}
}

View File

@@ -0,0 +1,169 @@
using Acr.UserDialogs;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.CurrentActivity;
using System;
using Xamarin.Forms;
using ZXing.Mobile;
namespace XXCpzs.Droid
{
[Activity(Label = "XXCpzs", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static Context mContext { get; private set; }
internal static MainActivity Instance { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
//var uiOpts = SystemUiFlags.LayoutStable | SystemUiFlags.LayoutFullscreen;
//LayoutStable表示布局稳定不随其他变动而变动
//LayoutFullscreen表示把布局拓宽到全屏幕
//Window.DecorView.SystemUiVisibility = (StatusBarVisibility)uiOpts;
//把标题栏设置为透明色
// Window.SetStatusBarColor(Android.Graphics.Color.Argb(0, 0, 0, 0));
base.OnCreate(savedInstanceState);
Instance = this;
mContext = this;
UserDialogs.Init(this);
Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
//初始化代码
CrossCurrentActivity.Current.Init(this, savedInstanceState);
MobileBarcodeScanner.Initialize(Application);
LoadApplication(new App());
DependencyService.Register<XXCpzs.Services.ITextToSpeechService, Services.TextToSpeechService>();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#region ----
/// <summary>
/// 使用DownloadManager下载安装文件
/// </summary>
/// <param name="context"></param>
/// <param name="apkAddress"></param>
public void DownloadUpdateFile(string apkAddress)
{
var apkFileName = System.IO.Path.GetFileName(apkAddress);
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(apkAddress));
// request.SetAllowedNetworkTypes(DownloadNetwork.Wifi);//网络环境
//request.SetDestinationInExternalPublicDir("download", "update1.apk");
request.SetDestinationInExternalFilesDir(this, Android.OS.Environment.DirectoryDownloads, apkFileName);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetMimeType("application/vnd.android.package-archive");
//设置通知信息
request.SetTitle(apkFileName);
request.SetDescription("软件更新");
//设置为可见和可管理
request.SetVisibleInDownloadsUi(true);
//设置为可被媒体扫描器找到
request.AllowScanningByMediaScanner();
request.SetAllowedOverRoaming(false);
//下载管理
DownloadManager downManager = (DownloadManager)this.GetSystemService(Context.DownloadService);
//获取此次下载的ID,返回一个唯一编号(用于识别通知来源)
var refrence = downManager.Enqueue(request);
// 注册广播监听系统的下载完成事件。
IntentFilter intentFilter = new IntentFilter(DownloadManager.ActionDownloadComplete);
var boradcastReceiver = new DownloadReceiver(refrence);
this.RegisterReceiver(boradcastReceiver, intentFilter);
/*备注:服务器端apk文件mime类型为application/vnd.android.package-archive
* 需要权限:android.permission.INTERNET和android.permission.WRITE_EXTERNAL_STORAGE
*/
}
/// <summary>
/// 自定义下载更新
/// </summary>
/// <param name="context"></param>
/// <param name="apkAddress"></param>
public void DownloadUpdateFile2(Context context, String apkAddress)
{
//权限检查
if (context.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
{
this.RequestPermissions(new string[] { Android.Manifest.Permission.WriteExternalStorage }, 1001);
return;
}
Java.IO.FileOutputStream outputStream = null;
System.IO.Stream inputStream = null;
Java.Net.HttpURLConnection connection = null;
Java.IO.File installFile = null;
try
{
var url = new Java.Net.URL(apkAddress);
connection = (Java.Net.HttpURLConnection)url.OpenConnection();
connection.ConnectTimeout = 60 * 1000;//1分钟
connection.ReadTimeout = 60 * 10 * 1000;
connection.Connect();
if (connection.ResponseCode != Java.Net.HttpStatus.Ok)
{
var errorMessage = connection.ResponseCode.ToString() + " " + connection.ResponseMessage;
return;
}
var contentLength = connection.ContentLength;
inputStream = connection.InputStream;
var downloadFile = Android.Net.Uri.FromFile(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads));
installFile = new Java.IO.File(downloadFile.Path, System.IO.Path.GetFileName(apkAddress));
outputStream = new Java.IO.FileOutputStream(installFile, false);//需要获取存储权限
byte[] data = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.Read(data, 0, data.Length)) > 0)
{
total += count;
outputStream.Write(data, 0, count);
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
if (outputStream != null)
outputStream.Close();
if (inputStream != null)
inputStream.Close();
if (connection != null)
connection.Disconnect();
if (installFile != null && installFile.Exists())
{
var installIntent = new Intent(Intent.ActionView);
installIntent.SetDataAndType(Android.Net.Uri.FromFile(installFile), "application/vnd.android.package-archive");
context.StartActivity(installIntent);
}
}
#endregion
}
}

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.01" package="com.xixingwl.xxcpzs" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="XXCpzs" android:icon="@drawable/icon"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</manifest>

View File

@@ -0,0 +1,34 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XXCpzs.Android")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XXCpzs.Android")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]

View File

@@ -0,0 +1,50 @@
Images, layout descriptions, binary blobs and string dictionaries can be included
in your application as resource files. Various Android APIs are designed to
operate on the resource IDs instead of dealing with images, strings or binary blobs
directly.
For example, a sample Android app that contains a user interface layout (main.xml),
an internationalization string table (strings.xml) and some icons (drawable-XXX/icon.png)
would keep its resources in the "Resources" directory of the application:
Resources/
drawable-hdpi/
icon.png
drawable-ldpi/
icon.png
drawable-mdpi/
icon.png
layout/
main.xml
values/
strings.xml
In order to get the build system to recognize Android resources, set the build action to
"AndroidResource". The native Android APIs do not operate directly with filenames, but
instead operate on resource IDs. When you compile an Android application that uses resources,
the build system will package the resources for distribution and generate a class called
"Resource" that contains the tokens for each one of the resources included. For example,
for the above Resources layout, this is what the Resource class would expose:
public class Resource {
public class drawable {
public const int icon = 0x123;
}
public class layout {
public const int main = 0x456;
}
public class strings {
public const int first_string = 0xabc;
public const int second_string = 0xbcd;
}
}
You would then use R.drawable.icon to reference the drawable/icon.png file, or Resource.layout.main
to reference the layout/main.xml file, or Resource.strings.first_string to reference the first
string in the dictionary file values/strings.xml.

14215
XXCpzs.Android/Resources/Resource.designer.cs generated Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="@android:color/white"
app:tabGravity="fill"
app:tabMode="fixed" />

View File

@@ -0,0 +1,9 @@
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/launcher_background" />
<foreground android:drawable="@mipmap/launcher_foreground" />
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/launcher_background" />
<foreground android:drawable="@mipmap/launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="launcher_background">#FFFFFF</color>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
</style>
<!-- Base theme applied no matter what API -->
<style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
<item name="windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="windowActionBar">false</item>
<!-- Set theme colors from https://aka.ms/material-colors -->
<!-- colorPrimary is used for the default action bar background -->
<item name="colorPrimary">#2196F3</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">#1976D2</item>
<!-- colorAccent is used as the default value for colorControlActivated
which is used to tint widgets -->
<item name="colorAccent">#FF4081</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight and colorSwitchThumbNormal. -->
<item name="windowActionModeOverlay">true</item>
<item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
</style>
<style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#FF4081</item>
</style>
</resources>

View File

@@ -0,0 +1,121 @@
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Content.Res;
using Android.Media;
using Android.OS;
using System;
using Xamarin.Forms;
using XXCpzs.Droid.Services;
using XXCpzs.Services;
[assembly: Dependency(typeof(CommonService))]
namespace XXCpzs.Droid.Services
{
public class CommonService : ICommonService
{
public string GetVersion()
{
string version = "1.00";
try
{
PackageManager packageManager = MainActivity.Instance.PackageManager;
// getPackageName()是你当前类的包名0代表是获取版本信息
PackageInfo packInfo = packageManager.GetPackageInfo(MainActivity.Instance.PackageName, 0);
version = packInfo.VersionName;
}
catch (PackageManager.NameNotFoundException e)
{
// e.printStackTrace();
}
return version;
}
public void CloseApp()
{
//App.Current.Quit();
Process.KillProcess(Process.MyPid());
}
public void UpdateApp(string DownloadUrl)
{
var thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
//更新方式1
FileDownload.DownloadUpdateFile(MainActivity.Instance, DownloadUrl);
//更新方式2
//DownloadUpdateFile2(context, upadtePackageAddress);
}))
{
IsBackground = true
};
thread.Start();
}
// Unique ID for our notification:
static readonly int NOTIFICATION_ID = 1000;
static readonly string CHANNEL_ID = "location_notification";
internal static readonly string COUNT_KEY = "count";
// Number of times the button is tapped (starts with first tap):
int count = 1;
public void SendNotity(string title, string content)
{
// 将当前按钮按下计数值传递给下一个活动:
var valuesForActivity = new Bundle();
valuesForActivity.PutInt(COUNT_KEY, count);
//当用户单击通知时,将启动第二个活动。
var resultIntent = new Intent(MainActivity.mContext, typeof(MainActivity));
// 将一些值传递给 Activity
resultIntent.PutExtras(valuesForActivity);
// 构建跨任务导航的后堆栈:
var stackBuilder = TaskStackBuilder.Create(MainActivity.mContext);
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
stackBuilder.AddNextIntent(resultIntent);
var resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
// 使用后堆栈创建PendingEntent
var builder = new Android.Support.V4.App.NotificationCompat.Builder(MainActivity.mContext, CHANNEL_ID)
.SetAutoCancel(true) // 当用户单击通知时,从通知区域中取消通知
.SetContentIntent(resultPendingIntent) // 当用户单击意图时启动此活动。
.SetContentTitle("Button Clicked") // 设置标题
.SetNumber(count) //在内容信息中显示计数
.SetSmallIcon(Resource.Drawable.ico) // 这是要显示的图标
.SetContentText($"The button has been clicked {count} times."); // 要显示的消息。
// 最后,发布通知
var notificationManager = Android.Support.V4.App.NotificationManagerCompat.From(MainActivity.mContext);
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
// 增加按钮按下次数
count++;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
//通知通道在API 26中是新的不是 支持库)。不需要创建通知
//Android旧版本上的频道。
return;
}
//var name = Resources.GetString(Resource.String.channel_name);
//var description =MainActivity.Instance. GetString("The count from MainActivity.");
var channel = new NotificationChannel(CHANNEL_ID, "Local Notifications", NotificationImportance.Default)
{
Description = "The count from MainActivity."
};
var notificationManager = (NotificationManager)MainActivity.mContext. GetSystemService(Context. NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}

View File

@@ -0,0 +1,171 @@
using Android.Content.PM;
using Android.OS;
using System;
using Xamarin.Forms;
using XXCpzs.Droid.Services;
using XXCpzs.Services;
using XXCpzs.Droid;
using Android.Net;
using Android.Locations;
using Android.Content;
using Android.Telephony;
using Xamarin.Essentials;
[assembly: Dependency(typeof(NetworkConnection))] //的作用是将该类依赖于程序集,以便在可移植平台底下实例化接口。
namespace XXCpzs.Droid
{
public class NetworkConnection : INetworkConnection
{
        //没有网络
        public const int NETWORKTYPE_INVALID = 0;
        //wap网络
        public const int NETWORKTYPE_WAP = 1;
        //2G网络
        public const int NETWORKTYPE_2G = 2;
        //3G和3G以上网络或统称为快速网络
        public const int NETWORKTYPE_3G = 3;
        //wifi网络
        public const int NETWORKTYPE_WIFI = 4;
public bool IsConnected { get; set; }
        //判断是否有网络连接
        public void CheckNetworkConnection()
{
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
IsConnected = true;
}
else
{
IsConnected = false;
}
}
        //检查启用了网络位置提供商报告
        public bool isNetLocEnabled()
{
LocationManager locMgr = MainActivity.mContext.GetSystemService(Context.LocationService) as LocationManager;
return locMgr.IsProviderEnabled(LocationManager.NetworkProvider);
}
        //判断是否有WIFI连接
        public bool isWifiConnected(Context context)
{
if (context != null)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager.GetNetworkInfo(ConnectivityType.Wifi);
                //NetworkInfo mWiFiNetworkInfo = mConnectivityManager.GetNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (mWiFiNetworkInfo != null)
{
return mWiFiNetworkInfo.IsAvailable;
}
}
return false;
}
        //判断Mobile网络是否可用
        public bool isMobileConnected(Context context)
{
if (context != null)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
NetworkInfo mMobileNetworkInfo = mConnectivityManager.GetNetworkInfo(ConnectivityType.Mobile);
                //NetworkInfo mMobileNetworkInfo = mConnectivityManager.GetNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mMobileNetworkInfo != null)
{
return mMobileNetworkInfo.IsAvailable;
}
}
return false;
}
        //检查飞行模式 - 我们要关闭飞机模式
        //public bool confirmAirplaneModeOff(Context context)
//{
//int airplaneSetting = Settings.System.GetInt(context.ContentResolver, Settings.System.AirplaneModeOn, 0);
            //int airplaneSetting = Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0);
            //return airplaneSetting == 0;
//}
        //确定网络位置提供程序是否真的可用
      //  public bool isNetlocUsable(Context context)
// {
// return isNetLocEnabled(context) && confirmAirplaneModeOff(context) && isWifiConnected(context) && isMobileConnected(context);
// }
        //判断是否是FastMobileNetWork将3G或者3G以上的网络称为快速网络
        private static bool isFastMobileNetwork(Context context)
{
TelephonyManager telephonyManager = (TelephonyManager)context.GetSystemService(Context.TelephonyService);
switch (telephonyManager.NetworkType)
{
case NetworkType.OneXrtt:
return false; // ~ 50-100 kbps  
                case NetworkType.Cdma:
return false; // ~ 14-64 kbps  
                case NetworkType.Edge:
return false; // ~ 50-100 kbps  
                case NetworkType.Evdo0:
return true; // ~ 400-1000 kbps  
                case NetworkType.EvdoA:
return true; // ~ 600-1400 kbps  
                case NetworkType.Gprs:
return false; // ~ 100 kbps  
                case NetworkType.Hsdpa:
return true; // ~ 2-14 Mbps  
                case NetworkType.Hspa:
return true; // ~ 700-1700 kbps  
                case NetworkType.Hsupa:
return true; // ~ 1-23 Mbps  
                case NetworkType.Umts:
return true; // ~ 400-7000 kbps  
                case NetworkType.Ehrpd:
return true; // ~ 1-2 Mbps  
                case NetworkType.EvdoB:
return true; // ~ 5 Mbps  
                case NetworkType.Hspap:
return true; // ~ 10-20 Mbps  
                case NetworkType.Iden:
return false; // ~25 kbps  
                case NetworkType.Lte:
return true; // ~ 10+ Mbps  
                case NetworkType.Unknown:
return false;
default:
return false;
}
}
        //获取网络状态wifi,wap,2g,3g.
        /// <summary>
        /// context 上下文 
        /// return int 网络状态 {@link #NETWORKTYPE_2G},{@link #NETWORKTYPE_3G}
        /// {@link #NETWORKTYPE_INVALID},{@link #NETWORKTYPE_WAP}* <p>{@link #NETWORKTYPE_WIFI} 
        /// </summary>
        public static int getNetWorkType(Context context)
{
int mNetWorkType = 0;
ConnectivityManager manager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
NetworkInfo networkInfo = manager.ActiveNetworkInfo;
if (networkInfo != null && networkInfo.IsConnected)
{
String type = networkInfo.TypeName;
if (type.Equals("WIFI".ToUpper()))
{
mNetWorkType = NETWORKTYPE_WIFI;
}
else if (type.Equals("MOBILE".ToUpper()))
{
String proxyHost = Proxy.DefaultHost;
                    //String proxyHost = android.net.Proxy.getDefaultHost();
                    //mNetWorkType = TextUtils.IsEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G) : NETWORKTYPE_WAP;
}
}
else
{
mNetWorkType = NETWORKTYPE_INVALID;
}
return mNetWorkType;
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace XXCpzs.Droid.Services
{
class NotifyService
{
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.Speech.Tts;
using XXCpzs.Services;
namespace XXCpzs.Droid.Services
{
public class TextToSpeechService : Java.Lang.Object, ITextToSpeechService, TextToSpeech.IOnInitListener,
#pragma warning disable CS0618
TextToSpeech.IOnUtteranceCompletedListener
#pragma warning restore CS0618
{
TextToSpeech speaker;
TaskCompletionSource<bool> tcsInitialize;
TaskCompletionSource<bool> tcsUtterance;
Task<bool> Initialize()
{
if (tcsInitialize != null)
return tcsInitialize.Task;
tcsInitialize = new TaskCompletionSource<bool>();
try
{
speaker = new TextToSpeech(MainActivity.Instance, this);
#pragma warning disable CS0618
speaker.SetOnUtteranceCompletedListener(this);
#pragma warning restore CS0618
}
catch (Exception ex)
{
tcsInitialize.TrySetException(ex);
}
return tcsInitialize.Task;
}
public async Task SpeakAsync(string text)
{
await Initialize();
if (tcsUtterance?.Task != null)
await tcsUtterance.Task;
tcsUtterance = new TaskCompletionSource<bool>();
// Set the utterance id so the completed listener fires
var parameters = new Dictionary<string, string>();
parameters.Add(TextToSpeech.Engine.KeyParamUtteranceId, new Guid().ToString());
// Use an obsolete overload so it works on older API levels
#pragma warning disable CS0618
speaker.Speak(text, QueueMode.Flush, parameters);
#pragma warning restore CS0618
await tcsUtterance.Task;
}
public void OnInit(OperationResult status)
{
if (status.Equals(OperationResult.Success))
tcsInitialize.TrySetResult(true);
else
tcsInitialize.TrySetException(new ArgumentException("Failed to initialize TTS engine."));
}
public void OnUtteranceCompleted(string utteranceId)
{
tcsUtterance.TrySetResult(true);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
speaker?.Stop();
speaker?.Shutdown();
speaker = null;
}
base.Dispose(disposing);
}
}
}

View File

@@ -0,0 +1,171 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C0C1A1B5-9459-42ED-96AA-632294020CFE}</ProjectGuid>
<ProjectTypeGuids>{EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TemplateGuid>{9AA2D3C6-3393-45F1-8E7C-5A9901728795}</TemplateGuid>
<OutputType>Library</OutputType>
<RootNamespace>XXCpzs.Droid</RootNamespace>
<AssemblyName>XXCpzs.Android</AssemblyName>
<AndroidApplication>True</AndroidApplication>
<AndroidResgenFile>Resources\Resource.designer.cs</AndroidResgenFile>
<AndroidResgenClass>Resource</AndroidResgenClass>
<AndroidManifest>Properties\AndroidManifest.xml</AndroidManifest>
<MonoAndroidResourcePrefix>Resources</MonoAndroidResourcePrefix>
<MonoAndroidAssetsPrefix>Assets</MonoAndroidAssetsPrefix>
<AndroidUseLatestPlatformSdk>false</AndroidUseLatestPlatformSdk>
<TargetFrameworkVersion>v9.0</TargetFrameworkVersion>
<AndroidEnableSGenConcurrent>true</AndroidEnableSGenConcurrent>
<AndroidUseAapt2>true</AndroidUseAapt2>
<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>portable</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AndroidLinkMode>None</AndroidLinkMode>
<AotAssemblies>false</AotAssemblies>
<EnableLLVM>false</EnableLLVM>
<AndroidEnableProfiledAot>true</AndroidEnableProfiledAot>
<BundleAssemblies>false</BundleAssemblies>
<AndroidUseAapt2>true</AndroidUseAapt2>
<AndroidUseSharedRuntime>true</AndroidUseSharedRuntime>
<EmbedAssembliesIntoApk>false</EmbedAssembliesIntoApk>
<AndroidCreatePackagePerAbi>false</AndroidCreatePackagePerAbi>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>portable</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AndroidManagedSymbols>true</AndroidManagedSymbols>
<AndroidUseSharedRuntime>true</AndroidUseSharedRuntime>
<AotAssemblies>false</AotAssemblies>
<EnableLLVM>false</EnableLLVM>
<AndroidEnableProfiledAot>false</AndroidEnableProfiledAot>
<BundleAssemblies>false</BundleAssemblies>
<EmbedAssembliesIntoApk>false</EmbedAssembliesIntoApk>
<AndroidCreatePackagePerAbi>false</AndroidCreatePackagePerAbi>
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Android" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xamarin.Forms" Version="4.3.0.908675" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Xamarin.Essentials" Version="1.3.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="DownloadReceiver.cs" />
<Compile Include="FileDownload.cs" />
<Compile Include="MainActivity.cs" />
<Compile Include="Resources\Resource.designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\CommonService.cs" />
<Compile Include="Services\NetworkConnection.cs" />
<Compile Include="Services\NotifyService.cs" />
<Compile Include="Services\TextToSpeechService.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\AboutResources.txt" />
<None Include="Assets\AboutAssets.txt" />
<None Include="Properties\AndroidManifest.xml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\Tabbar.xml" />
<AndroidResource Include="Resources\layout\Toolbar.xml" />
<AndroidResource Include="Resources\values\styles.xml" />
<AndroidResource Include="Resources\values\colors.xml" />
<AndroidResource Include="Resources\mipmap-anydpi-v26\icon.xml" />
<AndroidResource Include="Resources\mipmap-anydpi-v26\icon_round.xml" />
<AndroidResource Include="Resources\mipmap-hdpi\launcher_foreground.png" />
<AndroidResource Include="Resources\mipmap-mdpi\launcher_foreground.png" />
<AndroidResource Include="Resources\mipmap-xhdpi\icon.png" />
<AndroidResource Include="Resources\mipmap-xhdpi\launcher_foreground.png" />
<AndroidResource Include="Resources\mipmap-xxhdpi\icon.png" />
<AndroidResource Include="Resources\mipmap-xxhdpi\launcher_foreground.png" />
<AndroidResource Include="Resources\mipmap-xxxhdpi\icon.png" />
<AndroidResource Include="Resources\mipmap-xxxhdpi\launcher_foreground.png" />
<AndroidResource Include="Resources\drawable\xamarin_logo.png" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\XXCpzs\XXCpzs.csproj">
<Project>{84264E36-B135-4ECF-9C36-4E298D158A2E}</Project>
<Name>XXCpzs</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_cangku.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_chucang.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_customer.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_hh.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_login.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_order.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_pack.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_Quit.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_Register.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_resale.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_sale.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_search.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_th.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico_weixiu.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\icon.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\loading.gif" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\mipmap-hdpi\icon.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\drawable\ico.png" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\mipmap-mdpi\icon.png" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />
</Project>