四大组件知识梳理(一)

来源:互联网 发布:vagaa哇嘎画时代 mac 编辑:程序博客网 时间:2024/05/19 10:53

活动:

1、活动的使用

(1)创建活动:继承Activity,重写onCreate方法;

Public class FirstActivity extends Activity{    @override    Protected void onCreate(){    }}

(2)所有的活动都要在AndroidManifest.xml中进行注册:

<activity    android:name=" "    android:Label=" "    <intent-filter>        <action android:name="android.intent.action.MAIN"/>        <category android:name="android.intent.category.LAUNCHER"/>    </intent-filter></activity>

(3)活动的销毁:

销毁:

finish();

2.使用Intent在活动中穿梭

(1)显示Intent:

Intent intent=new Intent(this,TestActivity.class);startActivity(intent);

(2)隐式Intent:指定action和category

注册

<activity android:name=".SecondActivity">    <intent-filter>        <action android:name="com.example.activitytest.ACTION_START"/>        <category android:name="android.intent.category.DEFAULT"/>    </intent-filter></activity>……

识别:

button1.setOnClickListener(new OnClickLister(){    @Override    public void onClick(View v){        Intent intent=new intent("com.example.activitytest.ACTION_START");        //这里category为默认值,Android.intent.category.DEFAULT,startActivity()方法启动时会自动将category添加到Intent中,此处省略;        startActivity(intent);    }});

启用其他程序的活动:

public void onClick(View v){    Intent intent=new Intent(Intent.ACTION_VIEW);    Intent.setData(Uri.parse("http://www.baidu.com");    startActivity(intent);}

data标签中可以配置如下内容:

android:scheme;android:host;android:port;android:path;android:mimeType;android:geo;android:tel;//Intent.ACTION_DIAL;

[http Url格式、请求和响应](http://www.cnblogs.com/mengdd/archive/2013/05/26/3099776.html

(3)活动中传递数据

向下一个活动传递数据:

intent.putExtra("键名",value);//传递数据Intent intent=getIntent();//接收数据String data=intent.getStringExtra("键名")//.getStringExtra();.getIntExtra();getBooleanExtra();等;

返回数据给上一个活动

Intent intent= newIntent(FirstActivity.this,SecondActivity.class);startActivityForResult(intent,1);//请求被启动的活动返回数据;@Override   //返回结果的处理;Protected void onActivityResult(int requestCode,int resultCode,Intent data){swith(requestCode){case:1    if(requestCode==RESULT_OK){    Sting returnedData=data.getStringExtra("data_return");    ……            }            break;    default;    }}

Intent intent=new Intent(); //被请求活动加载数据;intent.putExtra("data_return","Hello FirstActivity");setResult(SERESULT_OK,intent);finish();

(4)隐式IntentFilter的匹配规则

1)一个过滤列表中的action、category、data可以有多个,所有的action、category、data分别构成不同的类别,同一类别的信息共同约束当前类别的匹配过程,只有一个Intent同时匹配action类别、category类别、data类别才算匹配,只有完全匹配才能成功启动Activity;

2)一个Activity中可以有多个intent-filter,一个intent只要能够匹配任何一组intent-filter即可成功启动Activity;

action类别
Intent匹配要求Intent中的action存在且必须和过滤规则中的其中一个action相同,action区分大小写,同时action必须存在,否则匹配失败;

category类别
Intent中可以没有category,如果有,所有的category必须和过滤规则中的其中一个category相同,同时为了隐式调用Activity,必须在intent-filter中指定“android.intent.category.DEFAULT”;

data类别

data的语法:
data由两部分组成:mimeType和URI
mimeType:媒体类型,如图片、文本、文件、视频、网址等;
URI结构:://:/[||]
URI的默认值为content和file;

data的匹配规则和action类似,要求Intent中必须含有data数据,并且data数据能够完全匹配过滤规则中的某一个data;

eg:<intent-filter><data android:mimeType="video/mpeg" android:scheme="http"……/></intent-filter>intent.setDataAndType(Uri.parse("http://abc"),"video/mpeg"

注意事项:
隐式调用Activity时,判断Activity是否能够匹配隐式的Intent:
判断方法:PackageManager的resolveActivity方法:找不到返回null;
PackageManager的queryIntentActivitys方法:返回所有成功匹配的信息;
Intent的ResolveActivity方法:找不到返回null;

public abstract List<ResolveInfo>queryIntentActivities(Intent intent,int flags);public abstract ResolveInfo resolveActivity(Intent intent,int falgs);

flags要使用MATCH_DEFAULT_ONLY这个标记位;这个标记位含义是仅仅匹配那些在intent-filter中声明了

一类比较重要的用来标明这是一个入口Activity的一组action和category:

<action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"

(5)活动的生命周期

活动的生命周期

异常情况下的声明周期

1)资源相关的系统配置发生改变导致Activity被杀死并重新创建


系统环境配置发生改变,onPause、onStop、onDestroy均会被调用;
onStop()被调用之前,调用onSaveInstanceState保存当前活动状态;当Activity被重新创建后,系统调用onRestoreInstanceState,并把Activity销毁时onSaveInstanceState方法保存的Bundle对象作为参数传递给onRestoreInstanceState
和onCreate方法;

每个View都有onSaveInstanceState 和onRestoreInstanceState方法;
保存和恢复View层次结构,系统工作流程:Activity意外终止——>调用onSaveInstanceState保存数据——>Activity委托window保存数据——>委托顶层容器(ViewGroup或DecorView)保存数据——>通知各个子元素保存数据;

2)资源内存不足导致低优先级的Activity被杀死

Activity优先级:
前台Activity>可见但非前台Activity>后台Activity;
进程没有四大组件在执行,很快被系统杀死;可以将后台工作放入Service中;

3)要想系统配置发生改变后,Activity不被创建

在AndroidMenifest.xml中设置Activity的configChanges属性

android:configChanges="orientation|keyboardHidden";

常用的有locale、orientation、keyboardHidden、screenSize;当Activity不被重建时系统调用Activity的onConfigurationChanged方法存储和恢复数据;

(6)Activity的启动模式

四种启动模式

standard模式:系统默认模式,每次启动都会有一个新的Activity被创建;多实例实现,在这种模式下,谁启动这个Activity,那么这个Activity就晕向在他的那个Activity所在的栈中;此时,ApplicationContext去启动Activity,需要指定FLAG_ACTIVITY_NEW_TASK标记位;

singleTop:栈顶复用模式,如果Activity位于任务栈的栈顶,那么Activity不会被创建,同时它的onNewInstance方法会被回调,通过此方法的参数我们可以取出当前请求的信息;

singleTask:栈内复用模式,单实例模式,只有栈内存在,就不会创建,系统回调onNewInstance方法,默认具有clearTop的效果;

singleInstance:单实例模式加强版的singleTask模式,具有此种模式的Activity只能单独位于一个任务栈中;

任务栈分为前台和后台任务栈,后台任务栈中的Activity位于暂停状态,用户可以通过切换将后台任务再次调到前台:
如果存在2个任务栈,目前前台任务栈为AB,后台任务栈为CD,假设CD的模式均为singleTask,那么请求D整个后台任务栈都会被切换到前台,这个时候后退列表就变成了ABCD;

TaskAffinity(任务相关性)

Activity所需的任务栈名:默认为当前应用的包名;

为每个Activity**单独指定TaskAffinity属性**时,属性值不能喝包名相同,否则相当于没有指定

TaskAffinity属性需要和singTask启动模式和allowTaskReparenting属性配合使用;

当TaskAffinity和singleTask启动模式配对使用的时候,它是具有该模式的Activity的目前任务栈的名字,待启动的Activity会运行在名字和TaskAffinity相同的任务栈中;

当TaskAffinity和allowTaskReparenting结合的时候,当一个应用A启动了应用B的某个Activity后,如果这个Activity得allowTaskReparenting属性为True时,那么当应用B被启动后,此Activity会直接从应用A的任务栈总转移到应用B的的任务栈中;

常用的Activity的Flags

FLAG_ACTIVITY_NEW_TASK:作用为“singleTask”启动模式;

FLAG_ACTIVITY_SINGLE_TOP :作用为“singleTop”启动模式;

FLAG_ACTIVITY_CLEAR_TOP:作用为具有此标记位的Activity,当她启动时,在同一任务栈中的所有位于它上面的Activity都要出栈;

FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS:作用为具有此标记的Activity不会出现在历史Activity的列表中,当我们不希望用户通过历史列表回到我们的Activity时这个标记比较有用,等同于在XML中指定Activity的属性 Android:excludeFromRcents=”true”;

(7)Activity的工作过程

服务:

(1)定义一个服务:继承Service,重写onBind()方法;

1)服务中常用的三个方法:

**onCreat():服务创建时调用
onStartCommand():每次服务启动时调用;
onDestroy:服务销毁时调用;**

2)服务必须在AndroidManifest.xml中注册:

<service andrioid:name=".MyService"></service>

3)启用和停止服务

//启用:Intent startIntent=new Intent(this,MyService.class);startService(startIntent);//停止:Intent stopIntent=new Intent(this,MyService.class);stopServiece(stopIntent);**//在MyService中任意位置调用stopSelf()方法均可停止服务;**//startService和stopService都是定义在Context类中;

4)绑定服务

①Service类

class XxxService extends Service{private IBinder binder = newXxxBinder();public IBinder onBind(Intent intent){return binder;}public int fun(int a){//服务提供的方法,但是不能直接调用...}private class XxxBinder extends Binder implements IXxxBinder{//面向接口编程public return fun1(int a){//对外暴露的APIreturn fun(a);//内部调用Service的方法}}}

②ServiceConnection

为一个接口,用于绑定和解绑定IBinder,因此需要创建一个类实现它;

class XxxServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//service为在onBind返回的IBinder//绑定Binder对象}@Overridepublic void onServiceDisconnected(ComponentName name) {//解绑定Binder对象}}

③bindService和unbindService

Intent intent=new Intent(this,XxxService);bindService(intent,serviceConnection,BING_AUTO_CREATE);unbindService(serviceConnection);

④当创建一个提供绑定的service时,你必须提供给一个IBinder,来提供客户和service交互的接口。

  有三种方法可以定义这个接口:
  1)继承Binder类;
  2)使用一个Messenger;
  3)使用AIDL
  

(5)服务的生命周期

1)Context的startService()方法调用,服务没有创建则调用onCreate()方法,回调onStartCommand()方法,服务都只存在一个实例,调用stopService()或stopSelf()方法,停止服务;

2)context的bindService()来获取一个服务的持久连接,回调服务中的onBind()方法,如果服务没有创建,onCreate()方法会先于onBind()方法;调用方获取onBind()方法返回的IBinder对象实例;

3)调用startService,又去调用stopService()方法,这是服务中的onDestroy()方法就会执行;当调用bindService()方法后,又去调用unbindService()方法,onDestroy()方法也会执行;当startService()方法和unbindService()方法同时调用,必须同时调用stopService和unbinderService()方法,onDestroy()才会执行;

(6)使用前台服务

public class MyService extends Service(){……@override    public void onCreate(){    super.onCreate();    Notification notification=new Notification(R.drawble.ic_launcher,"Notification comes",System.currentTimeMillis());    Intent notificationIntent=new Intent(this,MainActivity.class);    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0)    notification.setLatestEventInfo(this,"this is title","this is content",pendingIntent);    startForeground(1,notification);    }

(6)IntentService

public class myIntentService extends IntentService{    public myIntentService(){        super(" ");    }    @override    public void onHandleIntent(Intent intent){        Log.d("  ");    }    @Override    public void onDestory(){        super.onDestory();        Log.d(" ");    }}public class MainActivity extends Activity implements OnclickListenr{……Intent intentService=new Intent(this,MyIntentService.class);startService(intentService);……}
0 0
原创粉丝点击