搜索
您的当前位置:首页正文

【第一行代码】记录:笔记+bug修复+android版本升级适配

来源:步旅网

setData()函数

活动启动方式

在AndroidManifest.xml 活动下设置参数:
android:launchMode= "singleTop"//假如设置为singleTop模式
standard模式 每次该活动启动都会创建新活动
singleTop模式 活动启动时判断返回栈的栈顶是不是该活动,是的话直接使用,否则创建新活动
singleTask模式 每次该活动启动会检查返回栈中是否存在,如果存在,则会将直接使用改实例,并将这个活动之上的所有活动全部出栈,如果不存在则创建新活动
singleInstance模式 此活动启用会用一个新的返回栈来管理

获取全局context技巧

public class MyApplication extends Application {
privite static Context context;
@Override
public void onCreate() {
context = getApplicationContext();
}

public static Context getContext() {
return context;
}
}
在AndroidManifest.xml
<application
android:name=“packagename.MyApplication”

使用Intent传递对象

Serializable (效率低,简单)

使类继承Serializable,不用重写方法,然后就可以将一个类通过Intent传递
例如:有一个这样的类

Parcelable

使类继承Parcelable,需要重写describeContents()和writeToParcel()这两个方法
例子,还是上面的例子,其中…表示get和set函数

使用Parcelable方法为

在接收方代码为

创建定时任务

bug记录

在ActivityLifeCycleTest中DialogActivity闪退

Unable to start activity ComponentInfo{com.example.activitylifecycletest/com.example.activitylifecycletest.DialogActivity}: java.lang.IllegalStateException: 
You need to use a Theme.AppCompat theme (or descendant) with this activity.

解决办法,有两种方式
1.将

public class DialogActivity extends AppCompatActivity 

改成

public class DialogActivity extends Activity 

2.将

android:theme="@android:style/Theme.Dialog"

改成

android:theme="@style/Theme.AppCompat.Dialog"

项目路径更换后安装apk错误

Session 'app': Error Installing APKs

解决办法:

clean project
make project

RecyclerView会出先每个item占满一页的效果

解决办法

    implementation 'androidx.recyclerview:recyclerview:1.0.0'

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>//这要改过来

将fruit_item.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="wrap_content">//这要改过来

    <ImageView
        android:id="@+id/team_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/team_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

</LinearLayout>

Error inflating class fragment

在activity_main.xml中

//fragment 必须要有 android:id 和 android:name
    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.fragment.LeftFragment"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"/>

//如果是只需要一个fragment容器,不需要android:name 但是标签得改成 <FrameLayout
    <FrameLayout
        android:id="@+id/right_fragment"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"/>

自定义广播无法接收到消息

原因: 参考 https://www.cnblogs.com/fomin/p/9890913.html
因为在Android 8.0 及以上 在xml中注册的广播,在接收的时候收到了额外的限制,如果你的app目标等级是26及以上,将无法接收到xml注册的广播,这是google 为了app注册的静态广播导致耗电加的限制,具体请查看【https://developer.android.com/guide/components/broadcasts.html】

第一种方法
//在sendBroadcast(intent);前面加上
intent.setComponent(new ComponentName("com.example.broadcasttest",
                        "com.example.broadcasttest.MyBroadcastReceiver"));
//ComponentName() 参数1是自定义广播的包名,参数2是自定义广播的路径
第二种方法
private BroadcastReceiver broadcastReceiver ;
		//动态的接受广播
        broadcastReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.broadcasttest.MY_BROADCAST");
        registerReceiver(broadcastReceiver, filter);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: ");
                Intent intent = new Intent();
                intent.setAction("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
    @Override
    protected void onDestroy() {
        unregisterReceiver(networkChangeReceiver);
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

发送有序广播收不到第二个程序的toast

解决办法:在第二程序中也动态的接受广播

//MainActivity
public class MainActivity extends AppCompatActivity {
    
    private AnotherBroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        broadcastReceiver = new AnotherBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.broadcasttest.MY_BROADCAST");
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }
}
//AnotherBroadcastReceiver
public class AnotherBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "AnotherBroadcastReceive";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: ");
        Toast.makeText(context, "Received in AnotherBroadcastReceiver",
                Toast.LENGTH_SHORT).show();
    }
}

发送有序广播优先级无法确定

//一样的,动态的设置权限
broadcastReceiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.broadcasttest.MY_BROADCAST");
filter.setPriority(1000);//优先级加上这一句

本地广播

使用LocalBroadcastManager需要在build.gradle中添加
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

android device monitor找不着

查看SQLite 表格 显示 Permission denied

参考 https:///liying15/article/details/98462312
利用run-as进入路径下

adb shell
pm list package -3 
run-as com.example.databasetest
cd databases
//打开数据库
sqlite3

NotificationCompat.Builder()过时

修改点击事件代码如下

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_notice:
                NotificationManager manager = (NotificationManager)
                        getSystemService(NOTIFICATION_SERVICE);
                //添加下面三行
                NotificationChannel mChannel = new NotificationChannel(
                        "id", "name", NotificationManager.IMPORTANCE_LOW);
                manager.createNotificationChannel(mChannel);
              	//在NotificationCompat.Builder()方法传入第二个参数
                Notification notification = new NotificationCompat.Builder(this, mChannel.getId())
                        .setContentTitle("This is content title")
                        .setContentText("This is content text")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(
                                getResources(), R.mipmap.ic_launcher))
                        .build();
                manager.notify(1, notification);
                Log.d("TAG", "onClick: ");
                break;
                default:break;
        }
    }

调用摄像头出现错误

参考 https:///zerozff/article/details/101980543

将AndroidManifest.xml 中的 provider android:name改成:

android:name="androidx.core.content.FileProvider"

Video播放器

WebView出现net::ERR_CLEARTEXT_NOT_PERMITTED

参考 http://www.pianshen.com/article/9026283192/

将
http://www.baidu.com
改成
https://www.baidu.com

This Handler class should be static or leaks might occur (anonymous android.os.Handler)

//将书上的改成
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if(message.what == UPDATE_TEXT) {
                text.setText("Nice to meet you");
            }
            return false;
        }
    });

第十一章申请百度API的几个网址

在导入依赖库com.android.support:design发生 Version 28 (intended for Android Pie and below) is the last version of the legacy support library, so we recommend that you migrate to AndroidX libraries when using Android Q and moving forward. The IDE can help with this: Refactor > Migrate to AndroidX

将com.android.support:design改成com.google.android.material:material:1.0.0
相应的在activity.main.xml也要改成com.google.android.material.navigation.NavigationView
更多的依赖库映射参考:
https://developer.android.google.cn/jetpack/androidx/migrate

NavigationView 图标显示为黑白

加上
navigationView.setItemIconTintList(null);

获取不到 http://guolin.tech/api/china 的数据

因为从Android 6.0开始引入了对Https的推荐支持,与以往不同,Android P的系统上面默认所有Http的请求都被阻止了。
需要在在AnroidManifest.xml 中的 application 设置属性

<android:usesCleartextTraffic="true">

因篇幅问题不能全部显示,请点此查看更多更全内容

Top