Android的版本更新的非常频繁,这给开发带来了较大的困难。每次Android的升级,SDK也会随之带来一些更新,添加一些新的东西进去。在Android开发过程中经常会遇到Call requires API level 21 (current min is 16)这样的类似问题。开发Android的时候,我们需要确定所使用的SDK版本,比如通过Android Studio开发Android的话,工程创建好后,在build.gradle配置文件(如果工程中有多个模块,这个配置文件会有多个)中,会有以下类似配置信息:
android {
compileSdk 32
defaultConfig {
applicationId "app.at"
minSdk 16
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
...
}
这里的配置信息告诉了我们开发的Android应用最低兼容的SDK版本为16。那像上面的错误提示是说我们用到了21这个SDK版本以上的API,而我们当前开发的Android应用最低兼容的SDK版本为16,这样我们开发的Android应用最低兼容的SDK版本就变为21了。
另外如果我们使用了比最低兼容的SDK版本(minSdk 16)还高的SDK版本的API,如上面的错误提示,我们使用了21这个SDK版本以上的API,在Android Studio中会提示如上错误信息,我们可以在对应的方法上添加@RequiresApi来消除这个错误提示,如@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)。
@RequiresApi
在开发Android的时候常常会遇到这个Call requires API level 21 (current min is 16)这种类似错误提示,如下:
public class MyViewPager extends FrameLayout {
public MyViewPager(@NonNull Context context) {
super(context);
}
public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
其中在重写public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes)这个构造函数的时候,通常会调用父类的对应的构造函数,父类FrameLayout的这个构造函数是21这个SDK版本以上提供的API,就可能会出现以上错误提示。
只需要添加注解@RequiresApi就可以消除这个错误提示,如@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)。
Android界面UI设计主要采用布局文件的方式设计,编写很少的代码。当然也可以完全代码的方式来编写整个UI。采用布局文件这种方式偏设计点,UI上面的设计可以直接拖拽,布局也一目了然,开发效率上相对来说要高。完全采用代码来编写这种方式完全面向程序员的,能够更好的理解Android程序的运行。
布局文件这种方式在开发时作为辅助就好,这种方式也只能在设计UI上用用,最多就是一些简单的交互。在复杂的交互场景中还是要靠代码来实现,而且一个app肯定不只是一些UI界面,还有很多数据也要考代码来完成。尤其是整个程序运行中还涉及到很多资源要去管理,如Activity的整个生命周期的管理,生命时候要创建一个Activity,什么时候要去销毁这个Activity等等。
完全用代码的方式编写UI的话其实也挺简单的,编写的代码量也不算多,有时候代码还要比布局文件这种方式少。也就是不太直接,感受不到采用布局文件这种方式的可见的那种视觉感受。
应用
Context
android.content.Context
每个Activity都是一个上下文,所有Activity都继承了这个抽象类。
包括整个Android app应用也对应一个上下文。我们调用getApplicationContext方法获取的就是整个应用程序的上下文,由Application来定义。
Application
Android程序运行时有一个代表整个应用程序的实例,它是程序运行的上下文,上面我们通过getApplicationContext方法获取的整个应用程序的上下文就是这个实例。这个实例由android.app.Application定义,默认情况下就是Application的实例。
我们也可以自定义这个Application,对Application进行扩展。对Application扩展后,在AndroidManifest.xml文件中指定application标签属性android:name,这里的name指定的是应用程序的类名,如android:name="app.at.App"。
public class App extends android.app.Application {
public void onCreate() {
super.onCreate();
}
public void onTerminate() {
super.onTerminate();
}
}
Application的启动是在主线程中进行的。当我们自定义这个Application的时候,在主线程最好不要有网络相关的操作,否则会报以下错误。
java.lang.RuntimeException: Unable to create application app.at.App: android.os.NetworkOnMainThreadException
如果非要这样做的话,需要授权允许这样的操作。
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
}
或者我们可以授权允许所有的操作。
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
除了permitNetwork,还有permitDiskReads,permitDiskWrites,permitUnbufferedIo,permitResourceMismatches,permitCustomSlowCalls可以授权允许操作。
主题
Android提供了大量的主题风格,如Theme.NoTitleBar、Theme.NoTitleBar.Fullscreen、Theme.NoTitleBar.OverlayActionModes、Theme.WithActionBar、Theme.Light、Theme.Light.NoTitleBar、Theme.Light.NoTitleBar.Fullscreen、Theme.Black、Theme.Black.NoTitleBar、Theme.Black.NoTitleBar.Fullscreen、Theme.Wallpaper、Theme.Wallpaper.NoTitleBar、Theme.Wallpaper.NoTitleBar.Fullscreen、Theme.Translucent、Theme.Translucent.NoTitleBar、Theme.Translucent.NoTitleBar.Fullscreen等。这些主题风格在sdk/platforms/android-32/data/res/values/themes.xml中都有定义。
状态栏
设置状态栏颜色
调用窗口的setStatusBarColor方法可以设置状态栏颜色。比如我们有时候想将状态栏的颜色设置为透明色:setStatusBarColor(Color.TRANSPARENT);将状态栏设置为透明之后,状态栏就看不到了。其实也不是看不到,状态栏是透明了,看不到,但状态栏上面的网络信号标识、时间、电量标识还是可以看得到的,可能看得不明显。另外要注意的是,状态栏只是被设置为透明了,并不是就不见了,其实还在那里,还占用了屏幕空间。
半透明状态栏
设置半透明状态栏是通过窗口的FLAG_TRANSLUCENT_STATUS来标志的,参考WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS的定义。如果需要半透明状态栏,就添加窗口的这个标志,否则的话就清除这个标志。
添加这个标志可以调用窗口的addFlags方法:addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);清除这个标志可以调用窗口的clearFlags方法:clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS的定义
public static final int FLAG_TRANSLUCENT_STATUS = 0x04000000;
需要注意的是,半透明状态栏带最小系统提供背景保护。并且是浮在窗口顶部的,页面直接从窗口顶部开始显示,而不是从状态栏下面开始显示。状态栏不会将页面给顶下来。
状态栏高度
private int getStatusBarHeight() {
int height = 0;
int resId = getResources().getIdentifier("status_bar_height",
"dimen", "android");
if (resId > 0) {
height = getResources().getDimensionPixelSize(resId);
}
return height;
}
导航栏
半透明导航栏
设置半透明导航栏是通过窗口的FLAG_TRANSLUCENT_STATUS来标志的,参考WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS的定义。如果需要半透明导航栏,就添加窗口的这个标志,否则的话就清除这个标志。
添加这个标志可以调用窗口的addFlags方法:addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);清除这个标志可以调用窗口的clearFlags方法:clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS的定义
public static final int FLAG_TRANSLUCENT_STATUS = 0x04000000;
需要注意的是,半透明导航栏带最小系统提供背景保护。并且是浮在窗口底部的,页面直接显示到窗口底部结束,而不是到导航栏上面显示结束。导航栏不会将页面给顶上去。
隐藏导航栏
WindowManager.LayoutParams params = getWindow().getAttributes();
params.systemUiVisibility =
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
getWindow().setAttributes(params);
窗口
屏幕
全屏
设置为全屏是通过窗口的FLAG_FULLSCREEN来标志的,参考WindowManager.LayoutParams.FLAG_FULLSCREEN的定义。如果需要全屏,就设置窗口的这个标志,否则的话就清除这个标志。
设置这个标志可以调用窗口的setFlags方法:setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);清除这个标志可以调用窗口的clearFlags方法:clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
WindowManager.LayoutParams.FLAG_FULLSCREEN的定义
public static final int FLAG_FULLSCREEN = 0x00000400;
代码示例:
private int flags;
@Override
public void onClick(View v) {
if ((flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
}
绘图
在所有的视图中有一个onDraw方法。View中的onDraw定义如下:
protected void onDraw(Canvas canvas) {
}
重写onDraw方法,重绘TextView:
class TextItemView extends TextView {
public TextItemView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
super.onDraw(canvas);
paint.setColor(Color.BLACK);
canvas.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1, paint);
}
}
截屏
视图快照
public class Snapshot {
public static Bitmap createBitmapSnapshot(Fragment fragment, View view) {
DisplayMetrics dm = fragment.getResources().getDisplayMetrics();
return createBitmapSnapshot(dm, view);
}
public static Bitmap createBitmapSnapshot(Context context, View view) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return createBitmapSnapshot(dm, view);
}
public static Bitmap createBitmapSnapshot(DisplayMetrics dm, View view) {
int width = dm.widthPixels;
int height = dm.heightPixels;
int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
view.layout(0, 0, width, height);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.TRANSPARENT);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
view.draw(canvas);
return bitmap;
}
}
文件操作
数据目录
用于存放Android应用所有私有文件的目录,这个目录可以通过Context的getDataDir方法获得。在开发Android应用时,最好不要直接使用这个目录,这个路径可能会随着时间的推移而改变。
缓存目录
Android应用的缓存目录,这个目录可以通过Context的getCacheDir方法获得。
文件目录
通过openFileOutput方法创建的文件存放的目录,这个目录可以通过Context的getFilesDir方法获得。
Android 应用私有文件操作
私有文件存放在/data/data/<app>目录下。
如下
/data/data/<app>/files/IMG_20220325_231218.jpg
Context提供了一些私有文件相关操作的方法。如openFileOutput、openFileInput等。
public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;
FileOutputStream os = applicationContext.openFileOutput(name, Context.MODE_PRIVATE);
os.write(data, toIndex + 1, data.length - (toIndex + 1));
public abstract FileInputStream openFileInput(String name) throws FileNotFoundException;
private InputStream getInputStream() throws IOException {
return context.openFileInput(path);
}
这两个方法都需要指定一个文件名参数name,文件名不能包含路径,即不能包含“path separators”部分。openFileOutput方法还需要指定一个mode参数,用于指定操作模式。文件操作模式可以指定为MODE_PRIVATE、MODE_WORLD_READABLE、MODE_WORLD_WRITEABLE、以及MODE_APPEND,可以参考FileMode注解。
@IntDef(flag = true, prefix = { "MODE_" }, value = {
MODE_PRIVATE,
MODE_WORLD_READABLE,
MODE_WORLD_WRITEABLE,
MODE_APPEND,
})
@Retention(RetentionPolicy.SOURCE)
public @interface FileMode {}
IMG_20220325_231218.jpg: open failed: ENOENT (No such file or directory)
java.io.FileNotFoundException: IMG_20220325_231218.jpg: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileInputStream.<init>(FileInputStream.java:160)
at java.io.FileInputStream.<init>(FileInputStream.java:115)
at com.zhenglv.libmy.Image.getInputStream(Image.java:24)
at com.zhenglv.libmy.Image.<init>(Image.java:18)
at com.zhenglv.libmy.Client.readPacket(Client.java:313)
at com.zhenglv.libmy.Client.run(Client.java:219)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Linux.open(Native Method)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
at libcore.io.IoBridge.open(IoBridge.java:478)
at java.io.FileInputStream.<init>(FileInputStream.java:160)
at java.io.FileInputStream.<init>(FileInputStream.java:115)
at com.zhenglv.libmy.Image.getInputStream(Image.java:24)
at com.zhenglv.libmy.Image.<init>(Image.java:18)
at com.zhenglv.libmy.Client.readPacket(Client.java:313)
at com.zhenglv.libmy.Client.run(Client.java:219)
IMG_20220325_231218.jpg: open failed: EROFS (Read-only file system)
java.io.FileNotFoundException: IMG_20220325_231218.jpg: open failed: EROFS (Read-only file system)
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
at com.zhenglv.libmy.Client.readPacket(Client.java:303)
at com.zhenglv.libmy.Client.run(Client.java:217)
Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)
at libcore.io.Linux.open(Native Method)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
at libcore.io.IoBridge.open(IoBridge.java:478)
at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
at com.zhenglv.libmy.Client.readPacket(Client.java:303)
at com.zhenglv.libmy.Client.run(Client.java:217)
网络
Http
W/System.err: java.io.IOException: Cleartext HTTP traffic to 192.168.0.3 not permitted
W/System.err: at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
W/System.err: at app.at.App.onStart(App.java:122)
W/System.err: at app.at.Start$1.run(Start.java:31)
W/System.err: at android.os.Handler.handleCallback(Handler.java:938)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:223)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7656)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
在配置清单AndroidManifest.xml中application标签中指定android:usesCleartextTraffic="true"。
或者在res/xml目录下建立一个network_security_config.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
然后在配置清单AndroidManifest.xml中application标签中指定android:networkSecurityConfig="@xml/network_security_config"
摄像头
Android提供了一个Camera类,注意是android.hardware.Camera,不是android.graphics.Camera。这是一个相机类,准确的说是一个摄像头类。
打开摄像头
Camera camera = Camera.open();
这个方法打开的是一个后置摄像头。
public static Camera open() {
int numberOfCameras = getNumberOfCameras();
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
return new Camera(i);
}
}
return null;
}
另外还有一个方法
public static Camera open(int cameraId) {
return new Camera(cameraId);
}
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.at/app.at.Camera}: java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.<init>(Camera.java:557)
at android.hardware.Camera.open(Camera.java:420)
at ***.***.***.onCreate(***.java:54)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
设置预览显示
在正确打开摄像头之后,需要设置预览显示,以便将摄像头投影进来的画面显示在一个预览显示上,所以这里会有一个Surface,中文理解为“面”或者“平面”。摄像头影射进来的画面就投影到这个Surface上。
Android通过Camera的setPreviewDisplay将摄像头影射进来的画面就投影到这个Surface上。
public final void setPreviewDisplay(SurfaceHolder holder) throws IOException {
if (holder != null) {
setPreviewSurface(holder.getSurface());
} else {
setPreviewSurface((Surface)null);
}
}
不过这里设置并不直接是一个Surface对象,而是一个SurfaceHolder对象。Android并没有提供一个创建这样一个Surface的方法,通常也不会直接对这个Surface进行操作。SurfaceHolder可以理解为是Surface的持有者,这是一种很好的设计。对Surface的操作都通过SurfaceHolder来进行。
public interface SurfaceHolder {
/** @deprecated this is ignored, this value is set automatically when needed. */
@Deprecated
public static final int SURFACE_TYPE_NORMAL = 0;
/** @deprecated this is ignored, this value is set automatically when needed. */
@Deprecated
public static final int SURFACE_TYPE_HARDWARE = 1;
/** @deprecated this is ignored, this value is set automatically when needed. */
@Deprecated
public static final int SURFACE_TYPE_GPU = 2;
/** @deprecated this is ignored, this value is set automatically when needed. */
@Deprecated
public static final int SURFACE_TYPE_PUSH_BUFFERS = 3;
/**
* Exception that is thrown from {@link #lockCanvas} when called on a Surface
* whose type is SURFACE_TYPE_PUSH_BUFFERS.
*/
public static class BadSurfaceTypeException extends RuntimeException {
public BadSurfaceTypeException() {
}
public BadSurfaceTypeException(String name) {
super(name);
}
}
/**
* A client may implement this interface to receive information about
* changes to the surface. When used with a {@link SurfaceView}, the
* Surface being held is only available between calls to
* {@link #surfaceCreated(SurfaceHolder)} and
* {@link #surfaceDestroyed(SurfaceHolder)}. The Callback is set with
* {@link SurfaceHolder#addCallback SurfaceHolder.addCallback} method.
*/
public interface Callback {
/**
* This is called immediately after the surface is first created.
* Implementations of this should start up whatever rendering code
* they desire. Note that only one thread can ever draw into
* a {@link Surface}, so you should not draw into the Surface here
* if your normal rendering will be in another thread.
*
* @param holder The SurfaceHolder whose surface is being created.
*/
void surfaceCreated(@NonNull SurfaceHolder holder);
/**
* This is called immediately after any structural changes (format or
* size) have been made to the surface. You should at this point update
* the imagery in the surface. This method is always called at least
* once, after {@link #surfaceCreated}.
*
* @param holder The SurfaceHolder whose surface has changed.
* @param format The new {@link PixelFormat} of the surface.
* @param width The new width of the surface.
* @param height The new height of the surface.
*/
void surfaceChanged(@NonNull SurfaceHolder holder, @PixelFormat.Format int format,
@IntRange(from = 0) int width, @IntRange(from = 0) int height);
/**
* This is called immediately before a surface is being destroyed. After
* returning from this call, you should no longer try to access this
* surface. If you have a rendering thread that directly accesses
* the surface, you must ensure that thread is no longer touching the
* Surface before returning from this function.
*
* @param holder The SurfaceHolder whose surface is being destroyed.
*/
void surfaceDestroyed(@NonNull SurfaceHolder holder);
}
/**
* Additional callbacks that can be received for {@link Callback}.
*/
public interface Callback2 extends Callback {
/**
* Called when the application needs to redraw the content of its
* surface, after it is resized or for some other reason. By not
* returning from here until the redraw is complete, you can ensure that
* the user will not see your surface in a bad state (at its new
* size before it has been correctly drawn that way). This will
* typically be preceeded by a call to {@link #surfaceChanged}.
*
* As of O, {@link #surfaceRedrawNeededAsync} may be implemented
* to provide a non-blocking implementation. If {@link #surfaceRedrawNeededAsync}
* is not implemented, then this will be called instead.
*
* @param holder The SurfaceHolder whose surface has changed.
*/
void surfaceRedrawNeeded(@NonNull SurfaceHolder holder);
/**
* An alternative to surfaceRedrawNeeded where it is not required to block
* until the redraw is complete. You should initiate the redraw, and return,
* later invoking drawingFinished when your redraw is complete.
*
* This can be useful to avoid blocking your main application thread on rendering.
*
* As of O, if this is implemented {@link #surfaceRedrawNeeded} will not be called.
* However it is still recommended to implement {@link #surfaceRedrawNeeded} for
* compatibility with older versions of the platform.
*
* @param holder The SurfaceHolder which needs redrawing.
* @param drawingFinished A runnable to signal completion. This may be invoked
* from any thread.
*
*/
default void surfaceRedrawNeededAsync(@NonNull SurfaceHolder holder,
@NonNull Runnable drawingFinished) {
surfaceRedrawNeeded(holder);
drawingFinished.run();
}
}
/**
* Add a Callback interface for this holder. There can several Callback
* interfaces associated with a holder.
*
* @param callback The new Callback interface.
*/
public void addCallback(Callback callback);
/**
* Removes a previously added Callback interface from this holder.
*
* @param callback The Callback interface to remove.
*/
public void removeCallback(Callback callback);
/**
* Use this method to find out if the surface is in the process of being
* created from Callback methods. This is intended to be used with
* {@link Callback#surfaceChanged}.
*
* @return true if the surface is in the process of being created.
*/
public boolean isCreating();
/**
* Sets the surface's type.
*
* @deprecated this is ignored, this value is set automatically when needed.
*/
@Deprecated
public void setType(int type);
/**
* Make the surface a fixed size. It will never change from this size.
* When working with a {@link SurfaceView}, this must be called from the
* same thread running the SurfaceView's window.
*
* @param width The surface's width.
* @param height The surface's height.
*/
public void setFixedSize(int width, int height);
/**
* Allow the surface to resized based on layout of its container (this is
* the default). When this is enabled, you should monitor
* {@link Callback#surfaceChanged} for changes to the size of the surface.
* When working with a {@link SurfaceView}, this must be called from the
* same thread running the SurfaceView's window.
*/
public void setSizeFromLayout();
/**
* Set the desired PixelFormat of the surface. The default is OPAQUE.
* When working with a {@link SurfaceView}, this must be called from the
* same thread running the SurfaceView's window.
*
* @param format A constant from PixelFormat.
*
* @see android.graphics.PixelFormat
*/
public void setFormat(int format);
/**
* Enable or disable option to keep the screen turned on while this
* surface is displayed. The default is false, allowing it to turn off.
* This is safe to call from any thread.
*
* @param screenOn Set to true to force the screen to stay on, false
* to allow it to turn off.
*/
public void setKeepScreenOn(boolean screenOn);
/**
* Start editing the pixels in the surface. The returned Canvas can be used
* to draw into the surface's bitmap. A null is returned if the surface has
* not been created or otherwise cannot be edited. You will usually need
* to implement {@link Callback#surfaceCreated Callback.surfaceCreated}
* to find out when the Surface is available for use.
*
* <p>The content of the Surface is never preserved between unlockCanvas() and
* lockCanvas(), for this reason, every pixel within the Surface area
* must be written. The only exception to this rule is when a dirty
* rectangle is specified, in which case, non-dirty pixels will be
* preserved.
*
* <p>If you call this repeatedly when the Surface is not ready (before
* {@link Callback#surfaceCreated Callback.surfaceCreated} or after
* {@link Callback#surfaceDestroyed Callback.surfaceDestroyed}), your calls
* will be throttled to a slow rate in order to avoid consuming CPU.
*
* <p>If null is not returned, this function internally holds a lock until
* the corresponding {@link #unlockCanvasAndPost} call, preventing
* {@link SurfaceView} from creating, destroying, or modifying the surface
* while it is being drawn. This can be more convenient than accessing
* the Surface directly, as you do not need to do special synchronization
* with a drawing thread in {@link Callback#surfaceDestroyed
* Callback.surfaceDestroyed}.
*
* @return Canvas Use to draw into the surface.
*/
public Canvas lockCanvas();
/**
* Just like {@link #lockCanvas()} but allows specification of a dirty rectangle.
* Every
* pixel within that rectangle must be written; however pixels outside
* the dirty rectangle will be preserved by the next call to lockCanvas().
*
* @see android.view.SurfaceHolder#lockCanvas
*
* @param dirty Area of the Surface that will be modified.
* @return Canvas Use to draw into the surface.
*/
public Canvas lockCanvas(Rect dirty);
/**
* <p>Just like {@link #lockCanvas()} but the returned canvas is hardware-accelerated.
*
* <p>See the <a href="{@docRoot}guide/topics/graphics/hardware-accel.html#unsupported">
* unsupported drawing operations</a> for a list of what is and isn't
* supported in a hardware-accelerated canvas.
*
* @return Canvas Use to draw into the surface.
* @throws IllegalStateException If the canvas cannot be locked.
*/
default Canvas lockHardwareCanvas() {
throw new IllegalStateException("This SurfaceHolder doesn't support lockHardwareCanvas");
}
/**
* Finish editing pixels in the surface. After this call, the surface's
* current pixels will be shown on the screen, but its content is lost,
* in particular there is no guarantee that the content of the Surface
* will remain unchanged when lockCanvas() is called again.
*
* @see #lockCanvas()
*
* @param canvas The Canvas previously returned by lockCanvas().
*/
public void unlockCanvasAndPost(Canvas canvas);
/**
* Retrieve the current size of the surface. Note: do not modify the
* returned Rect. This is only safe to call from the thread of
* {@link SurfaceView}'s window, or while inside of
* {@link #lockCanvas()}.
*
* @return Rect The surface's dimensions. The left and top are always 0.
*/
public Rect getSurfaceFrame();
/**
* Direct access to the surface object. The Surface may not always be
* available -- for example when using a {@link SurfaceView} the holder's
* Surface is not created until the view has been attached to the window
* manager and performed a layout in order to determine the dimensions
* and screen position of the Surface. You will thus usually need
* to implement {@link Callback#surfaceCreated Callback.surfaceCreated}
* to find out when the Surface is available for use.
*
* <p>Note that if you directly access the Surface from another thread,
* it is critical that you correctly implement
* {@link Callback#surfaceCreated Callback.surfaceCreated} and
* {@link Callback#surfaceDestroyed Callback.surfaceDestroyed} to ensure
* that thread only accesses the Surface while it is valid, and that the
* Surface does not get destroyed while the thread is using it.
*
* <p>This method is intended to be used by frameworks which often need
* direct access to the Surface object (usually to pass it to native code).
*
* @return Surface The surface.
*/
public Surface getSurface();
}
Android中可以通过SurfaceView来得到这个SurfaceHolder。
SurfaceView surfaceView = new SurfaceView(context);
SurfaceHolder holder = surfaceView.getHolder();
相机
可以通过PackageManager的hasSystemFeature方法检查相机在运行时是否可用,参考FEATURE_CAMERA的定义:android.hardware.camera。PackageManager还定义很多其他的Feature。
在Android模拟器环境下,hasSystemFeature(PackageManager.FEATURE_CAMERA)调用返回的是true。
系统相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, OpCode.Op_Take_Picture.get());
对应的,在onActivityResult方法中
if (requestCode == OpCode.Op_Take_Picture.get()) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
App app = (App) getApplicationContext();
Session session = app.getSession();
String filePath = Android.bitmapTo(app, bitmap,
UUID.randomUUID().toString() + "@" + session.getUserId() + ".jpg");
Uri uri = Uri.fromFile(new File(filePath));
onMediaUriAppend(uri);
}
需要注意的是,上面的代码虽然使用到了相机,但不需要添加相机对应的权限android.permission.CAMERA。如果加入了权限,如果在Android清单文件中加入了android.permission.CAMERA权限:
<uses-permission android:name="android.permission.CAMERA"/>
调用系统相机报如下异常:
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.android.camera2/com.android.camera.CaptureActivity } from ProcessRecord{3ade4ef 10290:app.at/u0a137} (pid=10290, uid=10137) with revoked permission android.permission.CAMERA
at android.os.Parcel.createExceptionOrNull(Parcel.java:2373)
at android.os.Parcel.createException(Parcel.java:2357)
at android.os.Parcel.readException(Parcel.java:2340)
at android.os.Parcel.readException(Parcel.java:2282)
at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3696)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1723)
at android.app.Activity.startActivityForResult(Activity.java:5314)
at android.app.Activity.startActivityForResult(Activity.java:5272)
at app.at.Post$5.onItemSelected(Post.java:571)
at ***.***.***.onClick(***.java:90)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.wm.ActivityStackSupervisor.checkStartAnyActivityPermission(ActivityStackSupervisor.java:1032)
at com.android.server.wm.ActivityStarter.executeRequest(ActivityStarter.java:999)
at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:669)
at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1100)
at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1072)
在Android清单文件中去掉android.permission.CAMERA权限,就不会出现上述情况。不过如果不去掉Android清单文件的android.permission.CAMERA权限也行,可以通过动态请求android.permission.CAMERA权限的方式:
if (ContextCompat.checkSelfPermission(Post.this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Post.this.requestPermissions(
new String[] {Manifest.permission.CAMERA},
OpCode.OP_CAMERA_PERMISSION.get());
}
然后在对应的onRequestPermissionsResult方法中调用系统相机:
if (requestCode == OpCode.OP_CAMERA_PERMISSION.get()) {
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.CAMERA)) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "相机权限申请成功", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if (intent.resolveActivity(context.getPackageManager()) != null) {
startActivityForResult(intent, OpCode.Op_Take_Picture.get());
//}
} else {
Toast.makeText(this, "相机权限申请失败", Toast.LENGTH_SHORT).show();
}
}
}
}
拍照
生物识别
BiometricPrompt
指纹识别
指纹
指纹(fingerprint)
FingerprintManager
构建
Android Studio构建的时候会生成一个BuildConfig.java文件,内容大概如下:
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "***";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "***";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
配置build变种
参考文档https://developer.android.google.cn/studio/build/build-variants?hl=zh-cn
productFlavors
productFlavors {
standard {
}
merchant {
}
}
All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com/r/tools/flavorDimensions-missing-error-message.html
这时我们需要配置一下变种维度
flavorDimensions 'version'
然后在每一种变种下面指定所属的变种维度
dimension "version"
flavorDimensions 'version'
productFlavors {
standard {
dimension 'version'
}
merchant {
dimension 'version'
}
}
如果给定的模块仅指定一个变种维度,那么Android Gradle插件会自动将该模块的所有变种分配给该维度。
即无需在每一种变种下面指定所属的变种维度
flavorDimensions 'version'
productFlavors {
standard {
}
merchant {
}
}
如果需要多个变种维度,可以这样
flavorDimensions "product", "version"
The apk for your currently selected variant cannot be signed. Please specify a signing configuration for this variant (standard-release).
- 大小: 57.2 KB
- 大小: 44 KB
- 大小: 107.4 KB
- 大小: 54.9 KB
分享到:
相关推荐
在Android开发领域,经典代码例子是开发者学习和提升技能的重要资源。这些例子涵盖了各种关键功能和组件的实现,有助于深入理解Android应用的工作原理。在这个压缩包中,我们可能找到了多个有关Android编程的示例...
在Android开发领域,初学者经常会面临许多挑战,如理解Android应用程序的基本架构、学习XML布局、掌握Java或Kotlin编程语言,以及如何与设备硬件交互等。"Android开发入门60个小案例+源代码"这个资源提供了丰富的...
该组件是基于开源库`Android-wheel`实现的,`Android-wheel`是一个适用于Android的滚轮选择器,它可以创建类似于iOS中PickerView的效果,让用户通过滚动来选取所需的数据。在省市区三级联动中,当用户在一级(省)...
在Android开发中,系统默认的日期和时间选择器虽然实用,但往往无法满足所有场景的需求。因此,开发者经常需要自定义日期选择器来提供更符合应用风格或特定功能的交互体验。这篇内容将深入探讨如何在Android中创建一...
在Android开发中,有时我们需要与远程数据库进行交互,例如SQLServer。这个场景通常是通过Web服务,如WebService来实现。本文将详细介绍如何在Android应用中利用WebService接口连接到SQLServer数据库,实现数据的增...
在Android开发中,串口通信(Serial Port Communication)是一种重要的技术,它允许设备之间通过串行接口进行数据交换。在Android Studio环境下实现串口通信,开发者可以构建与硬件设备交互的应用,例如读取传感器...
在Android开发中,为UI元素添加虚线、圆角和渐变效果是常见的需求,可以提升应用的视觉吸引力。下面将详细讲解如何实现这些效果。 ### 一、虚线(Dashed Line) 在Android中,我们可以使用`Shape Drawable`来创建...
Android应用开发的哲学是把一切都看作是组件。把应用程序组件化的好处是降低模块间的耦合性,同时提高模块的复用性。Android的组件设计思想与传统的组件设计思想最大的区别在于,前者不依赖于进程。也就是说,进程...
----------------------------------- Android 编程基础 1 封面----------------------------------- Android 编程基础 2 开放手机联盟 --Open --Open --Open --Open Handset Handset Handset Handset Alliance ...
在Android开发中,有时我们需要对显示的图片进行特殊处理,比如让图片呈现圆角或完全圆形。本知识点将深入探讨如何在Android应用中完美实现图片的圆角和圆形效果。 首先,我们来看如何实现图片的圆角效果。Android...
Android新编译规则Android.bp文件语法规则详细介绍,条件编译的配置案例。 Android.bp 文件首先是 Android 系统的一种编译配置文件,是用来代替原来的 Android.mk 文件的。在 Android7.0 以前,Android 都是使用 ...
在现代的移动应用开发中,JavaScript与原生平台之间的交互变得越来越常见,特别是在使用Android的WebView组件时。本文将深入探讨如何使用JavaScript调用Android的方法,并传递JSON数据,以实现两者之间的高效通信。 ...
【Android扫雷游戏开发详解】 在移动开发领域,Android Studio是Google推出的官方集成开发环境(IDE),用于构建Android应用程序。本项目"Android扫雷游戏"就是利用Android Studio进行开发的一个实例,旨在帮助初学...
第2篇为应用开发篇,通过实例介绍了Android UI布局、Android人机界面、手机硬件设备的使用、Android本地存储系统、Android中的数据库、多线程设计、Android传感器、Android游戏开发基础、Android与Internet,以及...
【Android 微信语音聊天Demo】是一个典型的移动应用开发示例,主要展示了如何在Android平台上构建类似微信的语音聊天功能。这个Demo包含了按钮状态切换、语音录制、本地存储、回放和加载等一系列关键操作,是Android...
Android SDK离线包合集(Android 4.0-5.0)。不用去Google下载,直接国内下载离线包,各版本文件独立,任意下载。手机流量上传了一部分,好心疼。如不能下载,请告诉我更新地址。 附上简单教程。 这是Android开发所...
在Android开发中,实现图片浏览的全屏缩放效果是一项常见的需求,特别是在社交应用中,如QQ好友动态和微信朋友圈。这种功能不仅需要提供良好的用户体验,还需要考虑性能和内存优化,因为图片通常较大,处理不当可能...
1. **Android SDK**:Android软件开发工具包(SDK)是开发Android应用的基础,包含了开发、调试和发布应用所需的所有工具,如Android Studio IDE、Java Development Kit(JDK)、模拟器以及各种版本的Android平台库...