Android知识点复习笔记

Android 系统架构:
Linux内核层:为Android的各种硬件提供底层的驱动
系统运行库层:通过C/C++提供主要的特性支持,例如SQlite提供数据库支持
应用框架层:提供了应用程序构建所要的API
应用层所有安装的应用程序都属于这一层

活动
1.Android 是使用Task(任务)来管理活动的,一个任务就是一组存放在栈里的活动的集合,这个栈被称为返回栈。

2.活动的生命周期具有4种状态
运行状态:处于返回栈顶部
暂停状态:不处于栈顶,但是可见
停止状态:不在栈顶,且完全不可见
销毁状态:从返回栈移除

3.7个回调方法
onCreate()在活动第一次创建时
onStart()在活动由不可见变为可见时
onResume()在活动准备好准备和用户进行交互时
onPause()系统准备去启动或者恢复一个活动时调用
onStop()在活动完全不可见时调用
onDestory()在活动被销毁之前
onRestart()活动由停止变为运行之前使用

4.活动在回收之前一定会调用onSaveInstanceState()回调方法,提供了一个Bundle用于保存数据,在下一次活动创建时能够传入参数

protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
String tempData="";
outState.putExtra("data_key",tempData);
}
protected void onCreate(Bundle savedInstanceState){
setContentView(R.layout.activity_main);
String tempData=savedInstanceState.getString("data_key");
}

5.活动的启动模式
standard:每次创建一个活动,会入栈处于栈顶
singleTop:如果活动在栈顶,则不会去创建新的实例
singleTask:如果活动在栈中存在,那么将会将活动上方的活动都出栈
singleInstance:启动一个新的返回栈来管理这个活动

控件
TextView,EditText,Button,ImageView,ProgressBar,AlterDialog,ProgressDialog
TextView:

android:layout_width,android:layout_height=match_parent\wrap_content\fill_parent
android:text="",android:textSize="",android:textColor="",android:gravity=""center|left|bottom|right|top";

Button:

android:textAllCaps="false"

EditText:

  • hint=”” maxLInes=”2″ .getText()//获取EditText的内容

ImageView:

  • android:src=”@drawable/img_2″ .setImageResource(R.id.img_2);

ProgressBar:

android:visibility="visible"/invisible/gone
setVisibility(View.VISIBLE);setVisibility(View.INVISIBLE);setVisibility(View.GONE)
int progress=progressBar.getProgress();

GONE:不显示且不占屏幕空间INViSIBLE:不显示,但占空间
AlterDialog:

dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
}});
dialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface,int which)});
dialog.show();

ProgressDialog:

setCancelable(false);//Back不会取消,只能通过ProgressDialog.dismiss()关闭对话框

设置监听:
1.

implements View.OnClickListner{
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v){
switch(v){
case R.id.button:
break;
default:
break;
}
}
button.setOnclickListener(new View.OnClickListener(){
public void onClick(View v){
}
});

布局 继承自ViewGroup
布局:
线性布局(LInearLayout)、
相对布局(RelativeLayout)、
帧布局(FrameLayout)、
表格布局(TableLayout)、
绝对布局(absoluteLayout)、
网格布局(GridLayout)、
约束布局(ConstraintLayout)
百分比布局PercentFrameLayout/PercentRelativeLayout
LinearLayout 属性:orientation=”vertical”|”horizontal”
layout_gravity用于控件的对其方式,gravity用于文字的对齐方式
top|bottom|left|right|center_vertical|center_horizontal
layout_weight(仅在LinearLayout布局中可以使用)
RelativeLayout 属性:android:layout_alignParentLeft、layout_alignParentRight…

layout_below=”@id/…”layout_above=””layout_toRightOf=””layout_toLeftOf=””
layout_alignLeft=”@id/…”左边缘对齐
PercentFrameLayout 属性:app:layout_widthPercent=”50%”app:layout_heightPercent=”50%”

使用布局title.xml:

隐藏系统自带的标题栏:actionbar.hide();

自定义控件:

public class TitleLayout implements LinearLayout{
public TitleLayout(Context context,AttributeSet attributeset){
super(context,attribute);
LayoutInflater.from(context).inflate(R.id.title,this);

}
}
<包名.TitleLayout
android:id="@+id/..."
android:layout_width=""
android:layout_height=""/>

LIstView只能实现纵向的滚动
1.布局文件中添加ListView

<LinearLayout
>
LinearLayout>
Private String[] data={"","",...};
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String>  arrayadapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
ListView listview=(ListView)findViewById(R.id.list_view);
listVIew.setAdapter(adapter);
}

自定义适配器

public class FruitAdapter extends ArrayAdapter<Fruit>{
private int resourcesId;
public FruitAdapter(Context context,int textViewResourceId,List<Fruit> objects){
super(context,textViewResourceId,objects);
resourcesId=textViewResourceId;
}
public View getView(int posotion,View convertVIew,ViewGroup parent){
Fruit fruit=getItem(position);
View view=LayoutFlater.from(getContext()).inflate(resourcesId,parent,false);
ImageView fruitImage=()...

TextView fruitName=()...

fruitImage.setImageResource(fruit.getImage());
fruitNmae.setText(fruit.getName());
return view;
}
}
public void getView(int posotion,View convertView,ViewGroup parent){
Fruit fruit=getItem(position);
View view;
ViewHolder holder;
if(convertView==null){
View view=LayoutFlater.from(getContext()).inflate(resourcesId,parent,false);
holder.fruitImage=()...

holder.fruitName=()...

view.setTag(holder);
}
else{
view= convertView;
holder=(ViewHolder) view.getTag();
}
fruitImage.setImageResource(fruit.getImage());
fruitNmae.setText(fruit.getName());
return view;
}
class ViewHolder{
ImageView fruitImage;
TextView fruitName;
}

ListView设置监听:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(){
}
});

RecyclerView:适配器需要继承RecyclerView.Adapter,且重写
public ViewHolder onCreteViewHolder(){}
public void onBindViewHolder(){}
public int getItemCount(){}

碎片
1.Fragment是一种可以嵌套在活动中的UI片段
2.

public class LeftFragment extends Fragment{
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View view=inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}

3.在活动中动态添加碎片

  • 3.1.创建带添加的碎片实例fragment=new LeftFragment();
  • 3.2.创建FragmentManager,FragmentManager fragmentManager=getSupportFragmentManager() ;
  • 3.3.开启一个事务,FragmentTransaction transaction=fragmentManager.beginTransaction();
  • 3.4.向容器添加碎片,transaction.replace(R.id.right_layout,fragment);
  • 3.5.提交事务,transaction.commit();

4.模拟返回栈
在3.4之后添加transaction.addToBackStack(null);

5.碎片与活动直接通信:

LeftFragment leftfragment=(LeftFragment)
getSupportFragmentManager().findFragmentById(R.id.right_fragment);
MainActivity activity=(MainActivity) getActivity();

6.生命周期:
状态:
运行:当一个碎片可见,且与它关联的活动处于运行状态时
暂停:当活动进入暂停状态
停止:当活动进入停止状态,或者在transaction.remove()/replace()后,调用transaction.addToBackState()方法
销毁:当活动进入销毁状态,或者在transaction.remove()/replace()后,没有transaction.addToBackState()方法

7.回调方法:
onAttach() 当碎片和活动创建关联的时候调用
onCreate()
onCreateView() :为碎片创建视图(加载布局)
onActivityCreated() :确保与碎片相关联的活动一定已经创建完毕的时候调用
onStart()
onResume()
onPause()
onStop()
onDestoryView() :当与碎片相关联的视图被移除的时候调用
onDestory()
onDetach()当碎片和活动解除关联的时候调用

layout-large,small,normal,xlarge
layout-ldpi,mdpi,hdpi,xhdpi,xxhdpi
layout-land横屏,port竖屏

广播
标准广播 Normal broadcasts:是一种完全异步执行的广播,在广播发出之后,所有的广播接收器几乎会在同一时间接收到这条广播消息,没有先后顺序,无法被截断。
有序广播 Ordered broadcasts:是一种同步执行的广播,在广播发出之后,同一时刻只会有一个广播接收器收到这条消息,当这个广播的逻辑执行结束之后,才会继续传递,前面的接收器可以截断广播。

1.动态注册:
1.创建一个广播接收器,继承BroadcastReceiver,重写onReceiver()方法。

class NewCreateReceiver extends BroadcastReceiver{
public void onReceiver(Context context,Intent intent){
}
}

2.新建一个InterFilter对象,addAction()添加广播

InterFilter interFilter=new InterFilter();
interFilter.addAction("广播字符串");

3.新建一个广播接收器对象

NewCreateReceiver receiver=new NewCreateReceiver();

4.通过registerReceiver(广播接收器对象,InterFilter对象)注册

registerReceiver(receiver,interFilter);

5.在OnDestroy(0方法中通过unregisterReceiver(广播接收器对象)注销

unregisterReceiver(receiver);

注:
动态注册的广播一定要取消注册;
如果需要一些对于用户敏感的操作,必须在配置文件AndroidManifest.xml中声明

<manifest xmls:android="http://">
<user-permission android:name="android.permission...."/>
manifest>

必须要在程序启动后才能收到广播

2.静态注册:
新建Broadcast Receiver
Exported:是否允许这个广播接收器接收本程序以外的广播
Enabled:是否启用这个广播接收器
必须在AndroidManifest.xml文件中注册:

<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<inter-filter>
<action android:name="android.intent.action...."/>
inter-filter>
receiver>

注:OnReceiver()中不能进行耗时操作

3.自定义广播:

Intent intent=new Intent(getPackageName(),"com.example.broadcasttest.MyBroadcastReceiver");
intent.setPackage("com.example.broadcasttest");
sendBroadcast(intent);

sendOrderedBroadcast(intent,null);

<inter-filter android:priority="100">
<action android:name="com.example."/>
inter-filter>

优先级高的先接收到,通过abortBroadcast()方法截断。

4.本地广播
为了解决系统全局广播的安全性问题,使用本地广播,广播只能在应用程序内部进行传递,并且广播接收器只能接收本应用程序发出的广播。

使用LocalBroadcastManager管理:

localBroadcastManager=LocalBroadcastManager.getInstance(this);

发送广播:

Intent intent=new Intent("");
localBroadcastManager.sendBroadcast(intent);

注册:

intentFilter=new interFilter();
intentFilter.addAction("");
localReceiver=new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver,intentFilter);
localBoradcastManager.unregisterReceiver(localReceiver);

Class LocalReceiver extends BroadcastReceiver{
public void onReceiver(Context context,Intent intent){

}
}


本地广播是无法通过静态注册的方式来接收的

Git
Git是一个开源的分布式版本控制工具
安装: sudo apt-get install git-core
配置:

git config --global user.name ""
git config --global user.email ""

仓库(Repository)是用于保存版本管理所需要信息的地方,所有本地提交的代码都会被提交到代码仓库中
创建: git init
利用ls -al查看.git文件夹
提交:

git add 文件夹/文件/.(全部)
git commit -m "描述信息"

在.gitignore文件中添加的文件都不会提交
查看修改的情况:

git status
git diff查看具体更改的内容
git diff app/src/main/java/com/example/providertest/ManiActivity.java

撤销修改(未add)

git checkout app/src/main/java/com/example/providertest/ManiActivity.java

撤销修改(已经add)
先取消添加git reset HEAD app/src/main/java/com/example/providertest/ManiActivity.java

git status
git checkout app/src/main/java/com/example/providertest/ManiActivity.java

查看修改日志

git log
git log id -1//看一行
git log id -1 -p//看具体

持久化
数据持久化就是将内存中的瞬时数据保存到存储设备中,包括文件存储、SharedPreferece存储以及数据库存储

文件存储
1.将数据存储到/data/data//files/目录

  • 3.1.利用openFileOutput()方法获取FileOutputStream对象
  • 3.2.利用OutputStreamWriter对象为参数,新建一个BufferedWriter对象
  • 3.3.通过write()方法写入data
    FileOutputStream out=openFileOutput(“文件名”,Context.MODE_PRIVATE);//覆盖//Context.MODE_APPEND追加
    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));
    writer.write();

2.读取文件数据

  • 2.1.利用openFileInput()方法获取FileInputStream对象
  • 2.2.利用BufferedReader对象,参数为InputStreamReader(in);
  • 2.3.利用readLine()逐行读出。
StringBuilder content=new StringBuilder();
FileInputStream in=openFileInput("文件名");
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String line=""
while(line=reader.readLIne()!=null){
content.append(line);
}

3.判断字符串为空或等于null:TextUtils.isEmpty(String **);

SharedPreferences存储使用键值对的方式进行存储
新建SharedPreferences对象的方法:

  • Contextd的getSharedPreferences()
  • Activity的getPreferences()
  • 通过PreferencesManager的getDefaultSharedPreferences()

SharedPreferences存储

  • 1.获取SharedPreferences.Editor对象
  • 2.Editor对象.put***()
  • 3.Editor对象.apply()提交
SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","tom");
editor.apply()

SharedPreferences读取

  • 1.获取SharedPreferences对象
  • 2.get***()
SharedPreferences pref=getSharedPerferences("data",MODE_PRIVATE);
String name=pref.getString("pref","");

内容提供器:用于不同程序之间的数据共享,允许一个程序访问另一个程序中的数据,还能保证数据的安全性。
运行时权限
1.在AndroidManifest.xml中添加权限声明:

<user-permission android:name=""/>
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.Permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},1)
}else{
};
public void onRequestPermissionResult(int requestCode,String[] permissions,int[] grantResults){
switch (requestCode){
case 1:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
}else{
}
break;
default:
break;
}
}

通知Notification
1.当应用程序不在前台运行,要向用户发出一些提示信息。

  • 1.1.创建NotificationManager对象
NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVER);
  • 1.2.构造NotificationChannel对象’ String id=”id”; NotificationChannel channel=new
   NotificationChannel(id,"123",NotificationManager.IMPORTANCE_LOW);
   manager.createNotificationChannel(channel)
  • 1.3.构造Notification对象
 Notification notification=new NotificationCompat.Builder(this,id) .setContentTiltle("This is
   content title") .setContentText("This ")
   .setWhen(System.currentTimeMillis)
   .setSmallIcon(R.drawable.small_icon)
   .setLargeIcon(BitmapFactory.decodeResources(getResources(),R.mipmsp.ic_launch))
   .build();
  • 1.4.
 manager.notify(1,notification);

2.为Notification设点击事件
PendingIntent:延迟行动的Intent,getActivity(),getBroadcast(),getService()
//参数:Context,0,Intent对象,0
最后一个参数确定PendingIntent的行为(FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT、FLATE_UPDATE_CURRENT)
.setContentIntent(PendingIntent对象)

Intent intent=new Intent(this,NotificationActivity.class);
PendingIntent pi=getActivity(this,0,intent,0);
Notification notification=new NotificationCompat.Builder(this,id)
.setContentTiltle()
.setContentText()
.setContentIntent(pi)
.setSmallIcon()
.setLargeIcon()
.setWhen(System.currentTimeMillis())
.build();
mamger.notify(1,notification);

3.取消通知.setAutoCancel(true)或manager.cancel(1);
音频.setSound(Uri.fromFile(“///”))
震动.setVibrate(new long[]{})
LED.setLights(Color.GREEN, ,)
默认.setDefaults(NotificationaCompat.DEFAULT_ALL)
长文本
.setStyle(new NotificationCompat.BigTextStyle().bigText(“”))
大图片
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getRources(),R.drawable…)))
优先级.setPriority(NotificationCompat.PRIORITY_MAX)HIGH,LOW,MIN,DEFAULT

4.播放音频
MediaPlayer
.setDataSource()
.prepare()
.start()
.pause()
.reset()
.stop()
.seekTo()
.release()
.isPlaying()

5.视频VideoView
.setVideoPath()
.start()
.pause()
.resume()//重头开
.seekTo()

服务service
1.服务是Android中实现后台运行的解决方案,适用于执行那些不需要和用户交互而且要求长期运行的任务。
2.服务的运行不依赖与任何用户界面,但依赖于创建服务的进程。
3.线程的两种创建方式:

Class MyThread extends Thread{
public void run(){
}
}
MyThread mythread=new MyThread();
mythread.start();
Class MyThread implements Runnable{
public void run(){
}
}
MyThread mythread=new MyThread();
new Thread(mythread).start();
或者new Thread(new Runnable(){
public void run(){}
}).start();

4.子线程中不能进行UI操作,可以通过异步消息处理机制

  • 4.1.新增一个Handler对象,重写handleMessage(Message msg)方法,switch(msg.what) public static final int UPDATE_TEXT=1; private Handler handler=new
    Handler(){ public void handleMessage(Message msg){ switch(msg.what){
    case UPDATE_TEXT: break; default: break; } } };
  • 4.2.在线程里通过handler发送Message new Thread(new Runnable(){ public void run(){ Message msg=new Message(); msg.what=UPDATE_TEXT;
    handler.sendMessage(msg); } }).start();

5.异步消息处理机制

  • 5.1.Message 传递的消息
  • 5.2.Handler 发送和处理消息
  • 5.3.MessageQueue 存放所有通过handler发送的消息,每个线程只有一个
  • 5.4.Looper MessageQueue的管家,执行loop()之后,就会进入无线循环,当发现Queue中存在消息,将消息取出,并传递给Handler的handlerMessage()方法中,每个线程只有一个Looper对象

6.使用AsyncTask:基于异步消息处理机制的
继承AsyncTask时需要传入的三个参数:Params:在执行ASyncTask需要传入的参数,可用于后台任务中使用;Progress后台执行如果要在界面显示当前的进度,则可以使用这个作为单位;Result:当任务执行结束如果需要对结果返回,则这个为返回的数据类型。
需重写的方法:
onPreExecute():任务开始时的界面初始化操作,比如显示一个进度对话框
doInBackground(Param…)处理耗时任务,不可以UI操作,如果想要反馈当前的执行进度,可以通过publishProgress(Progress)完成
onProgressUpdate(Progress…)当后台调用publishProgress()方法后会调用onProgressUpdate(),对UI操作
onPostExecute(Result)当后台任务执行完毕并通过return返回时,onPostExecute调用,进行UI操作

7.定义服务:

public class MyService extends Service{
public MyService(){
}

public IBinder onBind(Intent intent){
throw new UnsupportedOperationException("Not yet implemented")
}
public void onCreate(){}
public int onStartCommand(Intent intent,int flags,int startId){}
public void onDestroy(){}
}

8.回调
onCreate()在服务创建的时候调用
onStartCommand()在每次启动服务的时候调用,执行的动作在这里
onDestroy()在服务销毁的时候调用

9.在AndroidManifest.xml文件中注册:

<service
android:name=""
android:enabled=""
android:exported="">
service>

10.启动服务

Intent intent=new Intent(this,MyService.class);
startService(intent);

11.停止服务

Intent intent=new Intent(this,MyService.class);
stopService(intent);

或者服务自己调用 stopSelf()

12.活动和服务的通信:

  • 12.1.在Service中创建一个DownloadBinder类继承Binder,写一些服务的执行动作方法
    -12. 2.在Service中新建一个DownloadBinder对象
  • 12.3.在Service中的puclic IBinder onBind中返回DownloadBinder对象
  • 12.4.在Activity中创建一个DownloadBinder对象downloadBinder
  • 12.5.在Activity中创建一个ServiceConnection对象connection,重写ServiceConnection类中的
    onServiceConnected(ComponentName name,IBinder servicer){
    downloadBinder=(DownloadBinder)service; downloadBinder…//调用方法 }
    onServiceDisconnected(ComponentName name)

13.在Activity中
Intent intent=new Intent(this,MyService.class);
bindService(intent,connection,BIND_AUTO_CREATE);//活动和服务绑定后自动创建服务
unbindService(connection)

onCreate
onStartCommand()
onBind()
omDestroy()

startActivity()
stopActivity()
bindService()
unbindService()

14.前台服务

Intent intent=new Intent(this,MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
Notification no=new NotificationCompat.Builder(this)
.setContentTiltle()
.setContentText()
.setWhen()
.setContentIntent(pi)
.setSmallIcon()
.setLargeIcon(BItmapFactory.decodeResource(getresources(),R.))
.build();
startForeground(1,no);

45.如果在服务里处理一些耗时的逻辑,会ANR(Application Not Responding)
所以在startCommand()中应该开启线程,run(){…stopSelf();}

16.IntentService
新建一个myclass类继承IntentService

  • 1.无参数构造方法,调用父类有参构造,super(“MyIntentService”)
  • 2.onHandleIntent(Intent intent)方法中处理逻辑 在Activity中通过 INtent intent=new Intent(this,myclass.class); startService(intentService);

Original: https://blog.csdn.net/qq_39008113/article/details/120664824
Author: 王木木~~
Title: Android知识点复习笔记

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816260/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球