Android开发-BUG日记

前言

你好! 欢迎跟着梓芸一起来学习 Android 。本博客将从Android 第一行代码(第2版) 开始学习,并记录学习过程中遇到的bug及解决方法。欢迎关注!!!本文章持续更新~

广播的发送

Android API 29是安卓10(注意,从10开始,广播的发布需要指定接收包名),其中MainActivity.java中的发送按钮如此设置:

//设置广播包名(意思就是接收者的包名==发给谁==谁接收)
//intent.setPackage("com.example.fragmentbestpratice");
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //打印日志显示是否进入onclik逻辑
            Log.d("bugTest", "onClick: ");
            //设置广播
            Intent intent = new Intent("com.example.fragmentbestpratice.MY_BROADCAST");
            //设置广播包名(意思就是接收者的包名==发给谁==谁接收)
            intent.setPackage("com.example.fragmentbestpratice");
            //发布广播
            context.sendBroadcast(intent);
        }
    });
}

XML布局中,只有部分代码有提示,打属性的时候,没有提示

解决方法:在app/build.gradle中将compileSdkVersion、targetSdkVersion、buildToolsVersion降低至30以下,并Sync Now

修改前后比对

Android Device Monitor在AS里面找不到

因为自Android Studio 3.0开始弃用Android Device Monitor,那怎么看adv中存储的文件呢?
点击View - Tool Windows - Device File Explorer
在这里插入图片描述

adb shell 中执行指令时显示 Permission denied

是因为adb没有足够的指令,应当在命令行赋予管理员权限,在命令行中输入su 即可获取权限。
依然不行的话,换个虚拟机试试,有时候就是这样莫名其妙的…

在这里插入图片描述

Plugins 搜索不到 Database Naviga

输入字符越长越难搜,明明输入的一模一样但是还是搜不到,可以输入sql,然后往下翻,就能翻到这个插件了,因为是关联查询,所以和sql相关的都会出来。如果搜得到其他的,但是就是搜不到你想要的插件,建议查一下是不是因为插件版本和AS版本不兼容。
在这里插入图片描述

Android studio 英文输入字体变宽的解决方法

原因:英文输入被切换到全角
解决方法:shift+空格键 (在中文状态下按shift+空格键,再转换成英文状态就OK)

摄像头拍摄之后存储文件的 path 问题

AndroidManifest.xml 中定义了@xml/file_paths

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cameraalbumtest">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.cameraalbumtest.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

file_paths.xml 中 path=“” 会报错,书上还说留空…反正记住在里面填写斜杠 / 就好
在这里插入图片描述
解决方法:使用path=”/“ ,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="/"/>
</paths>

教材中 WebView 的教学无法访问 http://baidu.com

因为默认书写不能进行 http请求,而 https 可以,所以将链接改成 https 就解决问题,各代码如下所示:

adtivity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >
    <WebView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/web_view"/>
</LinearLayout>

MainActivity

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://baidu.com");
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.webviewtest">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

OkHttp 需要导入才能使用!

导入 OkHttp3 依赖库 : 在 Module 下的 build.gradle 配置文件中的 dependencies 节点 , 进行如下配置 ;

implementation 'com.squareup.okhttp3:okhttp:3.14.+'

同时也需要 设置jdk版本设置,在app / build.gradle 中添加:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
 }

调用Android系统的原生媒体播放器

  1. 音频播放器
  2. 视频播放器
  3. 系统相册

音频播放器播放指定音频

// fileList.get(position) 是我聚焦的文件列表中对应的文件(file 对象)
// mContext是我当前定义的 private Context mContext;//上下文
  uri = Uri.fromFile(fileList.get(position));
  intent.setDataAndType(uri, "audio");
  mContext.startActivity(intent);

在这里插入图片描述

String audioFilePath = "/sdcard/music/sample.mp3"; // 替换为音频文件的实际路径
File audioFile = new File(audioFilePath);
Uri audioUri = Uri.fromFile(audioFile);

视频播放器播放指定视频

 uri = Uri.parse(fileList.get(position).toString());//解析绝对地址
 // fileList.get(position).toString() ==  /storage/emulated/0/Movies/VID_20230810_083649.mp4
 intent.setComponent(new ComponentName("com.android.gallery3d", "com.android.gallery3d.app.MovieActivity"));
 intent.setDataAndType(uri, "video");
 mContext.startActivity(intent);

系统相册打开指定照片

这个就需要专门的方法来将 file 对象解析成 uri 了

//打开系统相册
 uri = getImageContentUri(mContext, fileList.get(position));
 intent = new Intent(Intent.ACTION_VIEW);
 intent.setData(uri);
 mContext.startActivity(intent);
//将路径转换成midea的uri
    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

provider android:authorities 命名的坑

命名的时候以 . 为间隔是访问不到的…

  • file.provider.authority
  • file_provider_authority

这个异常是由于从 Android 7.0 (API level 24) 开始,如果你的应用使用 file:// URI 访问另一个应用的文件,会抛出 FileUriExposedException 异常。这是为了增强应用间的安全性。为了解决这个问题,你可以使用 FileProvider。

以下是使用 FileProvider 解决此问题的示例代码:
首先,在 AndroidManifest.xml 中添加 FileProvider 的配置:

<application>
    ...
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="file_provider_authority"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
    ...
</application>

注意将 com.example.myapp.fileprovider 替换为你的应用程序的合适的 authorities。

在 res/xml 目录下创建一个名为 file_paths.xml 的 XML 文件,并添加如下内容:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="files" path="."/>
</paths>

最后,修改你的代码来使用 FileProvider:

// 获取txt文件的URI
File file = new File(getFilesDir(), "新建文本文档.txt");
Uri fileUri = FileProvider.getUriForFile(this, "com.example.myapp.fileprovider", file);

// 创建打开文件的Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "text/plain");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

// 启动活动
startActivity(intent);

隐藏 隐藏文件夹

   /**
     * 查找当前目录的符合条件的文件
     * 不能以绝对路径访问
     * 以开头为点的进行隐藏
     * @param file
     * @return
     */
    public static List<File> searchFile(File file) {
        ArrayList<File> list = new ArrayList<>();
        if (file.isDirectory()) {
            for (File listFile : file.listFiles()) {
                if (!listFile.getName().startsWith(".")) {
                    list.add(listFile);
                }
            }
        }
        return list;//返回子目录的所有物件
    }

布局调试步骤

在这里插入图片描述
打开预览版面,然后对着代码调,因为预览版不支持拖拽移动位置。textView中没字的话可以往里面加字,调完删掉就好

居中view

android:layout_gravity=“center”

单行显示

android:singleLine=“true”

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高冷的上官梓芸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值