Xamarin Android基本功能实现
前文已经配置好开发环境,接下来实现简单的扫描,拍照,相册,蓝牙,wifi,网络信息等基本功能。
主要目录
AndroidManifest.xml 应用权限管理
Main_axml 页面按钮等布局
MainActivity.cs 代码编辑页面
AndroidManifest.xml
注:版本号targetSdkVersion我的开始默认较高为27,写法有变动,调低为了21.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="CIPHERLABRK25Test1.CIPHERLABRK25Test1" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
<uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT" />
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true"></application>
</manifest>
Main_axml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:rowCount="6"
android:columnCount="2">
<Button
android:id="@+id/camera"
android:layout_columnSpan="2"
android:layout_width="fill_parent"
android:text="打开摄像头" />
<Button
android:id="@+id/bluetooth"
android:layout_columnSpan="2"
android:layout_width="match_parent"
android:text="蓝牙" />
<Button
android:id="@+id/btnScanQRCode"
android:layout_columnSpan="2"
android:layout_width="match_parent"
android:text="扫描二维码" />
<Button
android:id="@+id/wifi"
android:layout_columnSpan="2"
android:layout_width="match_parent"
android:text="wifi" />
<Button
android:id="@+id/net"
android:layout_columnSpan="2"
android:layout_width="match_parent"
android:text="显示网络信息" />
<Button
android:id="@+id/photo"
android:layout_columnSpan="2"
android:layout_width="match_parent"
android:text="打开相册" />
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="fill_parent"
android:layout_height="50.0dp"
android:id="@+id/imageView1"
android:adjustViewBounds="true" />
<TextView
android:id="@+id/tvMachineCode"
android:layout_marginRight="5dp"
android:textSize="20sp"
android:text="" />
<EditText
android:id="@+id/txtMachineCode"
android:textSize="20sp"
android:maxLength="50"
android:layout_width="fill_parent" />
</GridLayout>
MainActivity.cs主要代码如下
using System;
using Android.App;
using Android.Bluetooth;
using Android.Content;
using Android.Net.Wifi;
using Android.OS;
using Android.Provider;
using Android.Views;
using Android.Widget;
using Java.IO;
using ZXing.Mobile;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;
using Android.Support.V4.Content;
using Context = Android.Content.Context;
using Android.Runtime;
using Android.Database;
using Java.Util.Jar;
using Plugin.Media;
using Java.Lang;
using String = System.String;
using Android.Graphics;
using System.Collections.Generic;
using Android.Content.PM;
using Android.Net;
/*
* FastAndroidCamera 2.0.0
* xamarin.android.support.v4 23.3.0
* Zxing.net 0.15
* zxing.net.mobile 2.2.9
* */
namespace CIPHERLABRK25Test1
{
public static class App
{
public static File _file;
public static File _dir;
public static Bitmap bitmap;
}
[Activity(Label = "ZXing1", MainLauncher = true)]
public class MainActivity : Activity
{
private EditText txtMachineCode;
private Button Btnscanqrcode;
private Button TvActiviationCode;
private Button bluetooth;
private Button wifi;
private Button camera;
private Button net;
private Button photo;
// private ImageView _imageView;
private ImageView iv;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
MobileBarcodeScanner.Initialize(Application);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
txtMachineCode = FindViewById<EditText>(Resource.Id.txtMachineCode);
Btnscanqrcode = FindViewById<Button>(Resource.Id.btnScanQRCode);
bluetooth = FindViewById<Button>(Resource.Id.bluetooth);
wifi = FindViewById<Button>(Resource.Id.wifi);
camera = FindViewById<Button>(Resource.Id.camera);
photo = FindViewById<Button>(Resource.Id.photo);
iv = FindViewById<ImageView>(Resource.Id.imageView1);
net = FindViewById<Button>(Resource.Id.net);
Btnscanqrcode.Click += Btnscanqrcode_Click;
bluetooth.Click += bluetooth_Click;
wifi.Click += wifi_Click;
net.Click += net_Click;
photo.Click += photo_Click;
if (IsThereAnAppToTakePictures())
{
CreateDirectoryForPictures();
camera.Click += TakeAPicture; camera.Click += TakeAPicture;
}
}
private void net_Click(object sender, EventArgs e)
{
getCurrentNetType();
}
private void getCurrentNetType()
{
ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);
if (cm.ActiveNetworkInfo == null || cm.ActiveNetworkInfo.Equals(""))
{
txtMachineCode.Text = "xxxx";
}
else
{
txtMachineCode.Text = cm.ActiveNetworkInfo.TypeName;
}
}
//获取图册
private void photo_Click(object sender, EventArgs e)
{
File originalFile = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(
Android.OS.Environment.DirectoryPictures
), "zcb_pic_" + SystemClock.CurrentThreadTimeMillis() + ".png");
Intent _intentCut = new Intent(Intent.ActionGetContent, null);
_intentCut.SetType("image/*");// 设置文件类型
_intentCut.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(originalFile));
_intentCut.PutExtra(MediaStore.ExtraVideoQuality, 1);
StartActivityForResult(_intentCut, 0);
}
//拍照
private void TakeAPicture(object sender, EventArgs e)
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
App._file = new File(App._dir, String.Format("myPhoto_{0}.jpg", Guid.NewGuid())); //保存路径
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(App._file));
// StartActivityForResult(intent, 0);
StartActivity(intent);
}
private void CreateDirectoryForPictures()
{
App._dir = new File(
Environment.GetExternalStoragePublicDirectory(
Environment.DirectoryPictures), "CIPHERLABRK25Test1");
if (!App._dir.Exists())
{
App._dir.Mkdirs();
}
}
private bool IsThereAnAppToTakePictures()
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
IList<ResolveInfo> availableActivities = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
return availableActivities != null && availableActivities.Count > 0;
}
//wifi
private void wifi_Click(object sender, EventArgs e)
{
WifiManager wifi = (WifiManager)GetSystemService(Context.WifiService);
WifiInfo w = wifi.ConnectionInfo;
//wifi信息
txtMachineCode.Text = w.MacAddress + "**" + w.IpAddress;
if (wifi.IsWifiEnabled)
{
wifi.SetWifiEnabled(false);
}
else
{
wifi.SetWifiEnabled(true);
}
}
//蓝牙
private void bluetooth_Click(object sender, System.EventArgs e)
{
BluetoothAdapter localAdapter = BluetoothAdapter.DefaultAdapter;
if (!localAdapter.IsEnabled)
{
localAdapter.Enable();
}
else
{
localAdapter.Disable();
}
}
//扫描二维码
private ZXingScannerFragment scanFragment;
private View zxingOverlay;
//public override View OnCreateView(LayoutInflater inflater, ViewGroup p1, Bundle p2)
//{
// return inflater.Inflate(Resource.Layout.Scanner, null);
//}
private async void Btnscanqrcode_Click(object sender, System.EventArgs e)
{
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();
if (result == null)
{
return;
}
txtMachineCode.Text = result.Text.Trim();
}
//图片显示
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result ResultStatus, Intent data)
{
if (ResultStatus == Result.Ok)
{
/*
* 若系统版本低于4.4,返回原uri
* 若高于4.4,解析uri后返回
* */
if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
var url = Android.Net.Uri.Parse("file://" + GetPath(BaseContext, data.Data));
data.SetData(url);
//将本地相册照片显示在控件上
iv.SetImageURI(Android.Net.Uri.FromFile(new File(GetPath(BaseContext, data.Data))));
}
}
}
#region 高于 v4.4 版本 解析真实路径
public static String GetPath(Context context, Android.Net.Uri uri)
{
bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;
// DocumentProvider
if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
{
// ExternalStorageProvider
if (isExternalStorageDocument(uri))
{
String docId = DocumentsContract.GetDocumentId(uri);
String[] split = docId.Split(':');
String type = split[0];
if ("primary".Equals(type.ToLower()))
{
return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri))
{
String id = DocumentsContract.GetDocumentId(uri);
Android.Net.Uri contentUri = ContentUris.WithAppendedId(
Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri))
{
String docId = DocumentsContract.GetDocumentId(uri);
String[] split = docId.Split(':');
String type = split[0];
Android.Net.Uri contentUri = null;
if ("image".Equals(type))
{
contentUri = MediaStore.Images.Media.ExternalContentUri;
}
else if ("video".Equals(type))
{
contentUri = MediaStore.Video.Media.ExternalContentUri;
}
else if ("audio".Equals(type))
{
contentUri = MediaStore.Audio.Media.ExternalContentUri;
}
String selection = "_id=?";
String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else
if ("content".Equals(uri.Scheme.ToLower()))
{
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.LastPathSegment;
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".Equals(uri.Scheme.ToLower()))
{
return uri.Path;
}
return null;
}
public static String getDataColumn(Context context, Android.Net.Uri uri, String selection,
String[] selectionArgs)
{
ICursor cursor = null;
String column = "_data";
String[] projection = {
column
};
try
{
cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.MoveToFirst())
{
int index = cursor.GetColumnIndexOrThrow(column);
return cursor.GetString(index);
}
}
finally
{
if (cursor != null)
cursor.Close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static bool isExternalStorageDocument(Android.Net.Uri uri)
{
return "com.android.externalstorage.documents".Equals(uri.Authority);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static bool isDownloadsDocument(Android.Net.Uri uri)
{
return "com.android.providers.downloads.documents".Equals(uri.Authority);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static bool isMediaDocument(Android.Net.Uri uri)
{
return "com.android.providers.media.documents".Equals(uri.Authority);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static bool isGooglePhotosUri(Android.Net.Uri uri)
{
return "com.google.android.apps.photos.content".Equals(uri.Authority);
}
#endregion 高于 v4.4 版本 解析真实路径
}
}