安卓系统开发笔记

安卓应用

android底层开发17

【专题分析】使用Intent打开三方应用 · Android应用开发知识仓库 · 看云 (kancloud.cn)

1)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <activity
//.MainActivity代表包名+.MainActivity,即com.example.myapplication.MainActivity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
//设置LAUNCHER属性即设置当前activity为开机启动
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2)context

主要有app,service,activity这些子类,相当于系统的身份证。
Context context = this;
//textView要有context才能和系统打交道
TextView textView = new TextView(context);

3)intent

1、网上使用资料

AS往期版本:Android Studio 下载文件归档 | Android 开发者 | Android Developers (google.cn)

//意图,四大组件沟通桥梁,显性启动
        //显性启动
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        //隐形启动,启动网页
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("http://www.baidu.com"));
        startActivity(intent);
//intent.setFlag():参数
FLAG_ACTIVITY_BROUGHT_TO_FRONT     

  这个标志一般不是由程序代码设置的,如在launchMode中设置singleTask模式时系统帮你设定。

 

FLAG_ACTIVITY_CLEAR_TOP    

  如果设置,并且这个Activity已经在当前的Task中运行,因此,不再是重新启动一个这个Activity的实例,而是在这个Activity上方的所有Activity都将关闭,然后这个Intent会作为一个新的Intent投递到老的Activity(现在位于顶端)中。      例如,假设一个Task中包含这些ActivityABCD。如果D调用了startActivity(),并且包含一个指向Activity BIntent,那么,CD都将结束,然后B接收到这个Intent,因此,目前stack的状况是:AB。      上例中正在运行的Activity B既可以在onNewIntent()中接收到这个新的Intent,也可以把自己关闭然后重新启动来接收这个Intent。如果它的启动模式声明为“multiple”(默认值),并且你没有在这个Intent中设置FLAG_ACTIVITY_SINGLE_TOP标志,那么它将关闭然后重新创建;对于其它的启动模式,或者在这个Intent中设置FLAG_ACTIVITY_SINGLE_TOP标志,都将把这个Intent投递到当前这个实例的onNewIntent()中。      这个启动模式还可以与FLAG_ACTIVITY_NEW_TASK结合起来使用:用于启动一个Task中的根Activity,它会把那个Task中任何运行的实例带入前台,然后清除它直到根Activity。这非常有用,例如,当从Notification Manager处启动一个Activity。

 

FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET    

  如果设置,这将在TaskActivity stack中设置一个还原点,当Task恢复时,需要清理Activity。也就是说,下一次Task带着FLAG_ACTIVITY_RESET_TASK_IF_NEEDED标记进入前台时(典型的操作是用户在主画面重启它),这个Activity和它之上的都将关闭,以至于用户不能再返回到它们,但是可以回到之前的Activity。      这在你的程序有分割点的时候很有用。例如,一个e-mail应用程序可能有一个操作是查看一个附件,需要启动图片浏览Activity来显示。这个Activity应该作为e-mail应用程序Task的一部分,因为这是用户在这个Task中触发的操作。然而,当用户离开这个Task,然后从主画面选择e-mail app,我们可能希望回到查看的会话中,但不是查看图片附件,因为这让人困惑。通过在启动图片浏览时设定这个标志,浏览及其它启动的Activity在下次用户返回到mail程序时都将全部清除。

 

FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS    

  如果设置,新的Activity不会在最近启动的Activity的列表中保存。

 

FLAG_ACTIVITY_FORWARD_RESULT     

  如果设置,并且这个Intent用于从一个存在的Activity启动一个新的Activity,那么,这个作为答复目标的Activity将会传到这个新的Activity中。这种方式下,新的Activity可以调用setResult(int),并且这个结果值将发送给那个作为答复目标的Activity。

 

FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY     

  这个标志一般不由应用程序代码设置,如果这个Activity是从历史记录里启动的(常按HOME键),那么,系统会帮你设定。

 

FLAG_ACTIVITY_MULTIPLE_TASK     

  不要使用这个标志,除非你自己实现了应用程序启动器。与FLAG_ACTIVITY_NEW_TASK结合起来使用,可以禁用把已存的Task送入前台的行为。当设置时,新的Task总是会启动来处理Intent,而不管这是是否已经有一个Task可以处理相同的事情。      由于默认的系统不包含图形Task管理功能,因此,你不应该使用这个标志,除非你提供给用户一种方式可以返回到已经启动的Task。      如果FLAG_ACTIVITY_NEW_TASK标志没有设置,这个标志被忽略。

 

FLAG_ACTIVITY_NEW_TASK     

   如果设置,这个Activity会成为历史stack中一个新Task的开始。一个Task(从启动它的Activity到下一个Task中的Activity)定义了用户可以迁移的Activity原子组。Task可以移动到前台和后台;在某个特定Task中的所有Activity总是保持相同的次序。      这个标志一般用于呈现“启动”类型的行为:它们提供用户一系列可以单独完成的事情,与启动它们的Activity完全无关。      使用这个标志,如果正在启动的ActivityTask已经在运行的话,那么,新的Activity将不会启动;代替的,当前Task会简单的移入前台。参考FLAG_ACTIVITY_MULTIPLE_TASK标志,可以禁用这一行为。      这个标志不能用于调用方对已经启动的Activity请求结果。

 

FLAG_ACTIVITY_NO_ANIMATION    

  如果在Intent中设置,并传递给Context.startActivity()的话,这个标志将阻止系统进入下一个Activity时应用Acitivity迁移动画。这并不意味着动画将永不运行——如果另一个Activity在启动显示之前,没有指定这个标志,那么,动画将被应用。这个标志可以很好的用于执行一连串的操作,而动画被看作是更高一级的事件的驱动。

 

FLAG_ACTIVITY_NO_HISTORY     

  如果设置,新的Activity将不再历史stack中保留。用户一离开它,这个Activity就关闭了。这也可以通过设置noHistory特性。

 

FLAG_ACTIVITY_NO_USER_ACTION     

  如果设置,作为新启动的Activity进入前台时,这个标志将在Activity暂停之前阻止从最前方的Activity回调的onUserLeaveHint()。      典型的,一个Activity可以依赖这个回调指明显式的用户动作引起的Activity移出后台。这个回调在Activity的生命周期中标记一个合适的点,并关闭一些Notification。      如果一个Activity通过非用户驱动的事件,如来电或闹钟,启动的,这个标志也应该传递给Context.startActivity,保证暂停的Activity不认为用户已经知晓其Notification。

 

FLAG_ACTIVITY_PREVIOUS_IS_TOP     

   If set and this intent is being used to launch a new activity from an existing one, the current activity will not be counted as the top activity for deciding whether the new intent should be delivered to the top instead of starting a new one. The previous activity will be used as the top, with the assumption being that the current activity will finish itself immediately.

 

FLAG_ACTIVITY_REORDER_TO_FRONT    

  如果在Intent中设置,并传递给Context.startActivity(),这个标志将引发已经运行的Activity移动到历史stack的顶端。      例如,假设一个Task由四个Activity组成:A,B,C,D。如果D调用startActivity()来启动Activity B,那么,B会移动到历史stack的顶端,现在的次序变成A,C,D,B。如果FLAG_ACTIVITY_CLEAR_TOP标志也设置的话,那么这个标志将被忽略。

 

FLAG_ACTIVITY_RESET_TASK_IF_NEEDED

  If set, and this activity is either being started in a new task or bringing to the top an existing task, then it will be launched as the front door of the task. This will result in the application of any affinities needed to have that task in the proper state (either moving activities to or from it), or simply resetting that task to its initial state if needed.

 

FLAG_ACTIVITY_SINGLE_TOP     

  如果设置,当这个Activity位于历史stack的顶端运行时,不再启动一个新的。 
前名一个参数是应用程序的包名,后一个是这个应用程序的主ActivityIntent intent=new Intent();
intent.setComponent(newComponentName("com.droidnova.android.games.vortex",
"com.droidnova.android.games.vortex.Vortex"));
startActivity(intent);

从任意app,启动另外一个app的activity:
1.  Intent i = new Intent(); 
         ComponentName cn = new ComponentName("com.book.android2",  "com.book.android2.AndroidSearch"); 
         i.setComponent(cn); 
         i.setAction("android.intent.action.MAIN"); 
         startActivity(i); //or startActivityForResult(i, RESULT_OK); 
我用这种方法时,绝大部分应用可以启动,但是像RootExplorer却无法启动,出现FC对话框,因此建议使用下面这种方式:
2.   Intent it = new Intent("android.intent.action.MAIN");
it.setClassName("com.speedsoftware.rootexplorer","com.speedsoftware.rootexplorer.RootExplorer");
startActivity(it);

如果你需要启动一个你自己写的另一个app的activity,你可以在那个的menifest.xml里自定义activity的action:
<activity android:name=".MainActivity" android:label="@string/app_name"android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
<intent-filter>
  <action android:name="com.qylk.call.main" />    <!-- 自定义的action-->
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
  <category android:name="android.intent.category.DEFAULT" /><!--必须加上这个,否则下面无法直接使用自定的action-->
  </intent-filter>
  </activity>

其他地方启动它:Intent it = new Intent("com.qylk.call.main"); startActivity(it);

3.使用adb启动activity:
启动RootExolorer:
am start -a android.intent.action.MAIN -n com.speedsoftware.rootexplorer/.RootExplorer
启动系统设置:
am start -a android.settings.SETTINGS

附(转载):android系统Action常量(其实不算全)
android intent和intent action大全 

1.从google搜索内容 
Intent intent = new Intent(); 
intent.setAction(Intent.ACTION_WEB_SEARCH); 
intent.putExtra(SearchManager.QUERY,"searchString") 
startActivity(intent); 

2.浏览网页 
Uri uri = Uri.parse("http://www.google.com"); 
Intent it  = new Intent(Intent.ACTION_VIEW,uri); 
startActivity(it); 

3.显示地图 
Uri uri = Uri.parse("geo:38.899533,-77.036476"); 
Intent it = new Intent(Intent.Action_VIEW,uri); 
startActivity(it); 

4.路径规划 
Uri uri = Uri.parse("http://maps.google.com/maps?f=dsaddr=startLat%20startLng&daddr=endLat%20endLng&hl=en"); 
Intent it = new Intent(Intent.ACTION_VIEW,URI); 
startActivity(it); 

5.拨打电话 
Uri uri = Uri.parse("tel:xxxxxx"); 
Intent it = new Intent(Intent.ACTION_DIAL, uri);   
startActivity(it); 
 //<uses-permission id="android.permission.CALL_PHONE" /> 


6.调用发短信的程序 
Intent it = new Intent(Intent.ACTION_VIEW);    
it.putExtra("sms_body", "The SMS text");    
it.setType("vnd.android-dir/mms-sms");    
startActivity(it); 

7.发送短信 
Uri uri = Uri.parse("smsto:0800000123");    
Intent it = new Intent(Intent.ACTION_SENDTO, uri);    
it.putExtra("sms_body", "The SMS text");    
startActivity(it); 

String body="this is sms demo"; 
Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null)); 
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body); 
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true); 
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true); 
startActivity(mmsintent); 

8.发送彩信 
Uri uri = Uri.parse("content://media/external/images/media/23");    
Intent it = new Intent(Intent.ACTION_SEND);    
it.putExtra("sms_body", "some text");    
it.putExtra(Intent.EXTRA_STREAM, uri);    
it.setType("image/png");    
startActivity(it); 

StringBuilder sb = new StringBuilder(); 
sb.append("file://"); 
sb.append(fd.getAbsoluteFile()); 
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null)); 
// Below extra datas are all optional. 
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject); 
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body); 
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString()); 
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode); 
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent); 
startActivity(intent); 

9.发送Email 
Uri uri = Uri.parse("mailto:xxx@abc.com"); 
Intent it = new Intent(Intent.ACTION_SENDTO, uri); 
startActivity(it); 

Intent it = new Intent(Intent.ACTION_SEND);    
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");    
it.putExtra(Intent.EXTRA_TEXT, "The email body text");    
it.setType("text/plain");   
 
startActivity(Intent.createChooser(it, "Choose Email Client")); 
Intent it=new Intent(Intent.ACTION_SEND);      
String[] tos={
   "me@abc.com"};      
String[] ccs={
   "you@abc.com"};      
it.putExtra(Intent.EXTRA_EMAIL, tos);      
it.putExtra(Intent.EXTRA_CC, ccs);      
it.putExtra(Intent.EXTRA_TEXT, "The email body text");      
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");      
it.setType("message/rfc822");      
startActivity(Intent.createChooser(it, "Choose Email Client"));    

Intent it = new Intent(Intent.ACTION_SEND);    
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");    
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");    
sendIntent.setType("audio/mp3");    
startActivity(Intent.createChooser(it, "Choose Email Client")); 

10.播放多媒体   
Intent it = new Intent(Intent.ACTION_VIEW); 
Uri uri = Uri.parse("file:///sdcard/song.mp3"); 
it.setDataAndType(uri, "audio/mp3"); 
startActivity(it); 

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");    
Intent it = new Intent(Intent.ACTION_VIEW, uri);    
startActivity(it); 

11.卸载
Uri uri = Uri.fromParts("package", strPackageName, null);    
Intent it = new Intent(Intent.ACTION_DELETE, uri);    
startActivity(it); 

12.安装
Uri installUri = Uri.fromParts("package", "xxx", null); 
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri); 

13. 打开照相机 
    Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null); 
    this.sendBroadcast(i);
 
    long dateTaken = System.currentTimeMillis(); 
    String name = createName(dateTaken) + ".jpg"; 
    fileName = folder + name; 
    ContentValues values = new ContentValues(); 
    values.put(Images.Media.TITLE, fileName); 
    values.put("_data", fileName); 
    values.put(Images.Media.PICASA_ID, fileName); 
    values.put(Images.Media.DISPLAY_NAME, fileName); 
    values.put(Images.Media.DESCRIPTION, fileName); 
    values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileName); 
    Uri photoUri = getContentResolver().insert( 
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
    Intent inttPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    inttPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); 
    startActivityForResult(inttPhoto, 10); 

14.从gallery选取图片 
  Intent i = new Intent(); 
  i.setType("image/*"); 
  i.setAction(Intent.ACTION_GET_CONTENT); 
  startActivityForResult(i, 11); 

15. 打开录音机 
   Intent mi = new Intent(Media.RECORD_SOUND_ACTION); 
   startActivity(mi); 

16.显示应用详细列表       
Uri uri = Uri.parse("market://details?id=app_id");         
Intent it = new Intent(Intent.ACTION_VIEW, uri);         
startActivity(it);         
     


17.寻找应用      
刚才找app id未果,结果发现用package name也可以 
Uri uri = Uri.parse("market://details?id=<packagename>"); 
这个简单多了 
 
Uri uri = Uri.parse("market://search?q=pname:pkg_name");         
Intent it = new Intent(Intent.ACTION_VIEW, uri);         
startActivity(it); 
     
18.打开联系人列表            
           Intent i = new Intent(); 
           i.setAction(Intent.ACTION_GET_CONTENT); 
           i.setType("vnd.android.cursor.item/phone"); 
           startActivityForResult(i, REQUEST_TEXT); 

            Uri uri = Uri.parse("content://contacts/people"); 
            Intent it = new Intent(Intent.ACTION_PICK, uri); 
            startActivityForResult(it, REQUEST_TEXT); 

20.调用系统编辑添加联系人(高版本SDK有效): 
Intent it = new Intent(Intent.ACTION_INSERT_OR_EDIT); 
                it.setType("vnd.android.cursor.item/contact"); 
                // it.setType(Contacts.CONTENT_ITEM_TYPE); 
                it.putExtra("name", "myName"); 
                it.putExtra(android.provider.Contacts.Intents.Insert.COMPANY,  "organization"); 
                it.putExtra(android.provider.Contacts.Intents.Insert.EMAIL, "email"); 
                it.putExtra(android.provider.Contacts.Intents.Insert.PHONE,"homePhone"); 
                it.putExtra( android.provider.Contacts.Intents.Insert.SECONDARY_PHONE, 
                                "mobilePhone"); 
                it.putExtra(  android.provider.Contacts.Intents.Insert.TERTIARY_PHONE, 
                                "workPhone"); 
                it.putExtra(android.provider.Contacts.Intents.Insert.JOB_TITLE,"title"); 
                startActivity(it); 

21.调用系统编辑添加联系人(全有效): 
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT); 
            intent.setType(People.CONTENT_ITEM_TYPE); 
            intent.putExtra(Contacts.Intents.Insert.NAME, "My Name"); 
            intent.putExtra(Contacts.Intents.Insert.PHONE, "+1234567890"); 
            intent.putExtra(Contacts.Intents.Insert.PHONE_TYPE, Contacts.PhonesColumns.TYPE_MOBILE); 
            intent.putExtra(Contacts.Intents.Insert.EMAIL, "com@com.com"); 
            intent.putExtra(Contacts.Intents.Insert.EMAIL_TYPE,                    Contacts.ContactMethodsColumns.TYPE_WORK); 
            startActivity(intent); 



23.最基本的share 信息的intent,可以传一段text信息到各个手机上已安装程序:如SMS,Email,sina微波,米聊,facebook,twitter等等 
            Intent it = new Intent(Intent.ACTION_SEND);     
    it.putExtra(Intent.EXTRA_TEXT, "The email subject text"); 
            it.setType("text/plain"); 
            startActivity(Intent.createChooser(it, "Choose Email Client")); 
          

intent action大全: 
ACTION_MAIN                         作为一个主要的进入口,而并不期望去接受数据 
ACTION_VIEW                         向用户去显示数据 
ACTION_ATTACH_DATA                  用于指定一些数据应该附属于一些其他的地方,例如,图片数据应该附属于联系人 
ACTION_EDIT                         访问已给的数据,提供明确的可编辑 
ACTION_PICK                         从数据中选择一个子项目,并返回你所选中的项目 
ACTION_CHOOSER                      显示一个activity选择器,允许用户在进程之前选择他们想要的 
ACTION_GET_CONTENT                  允许用户选择特殊种类的数据,并返回(特殊种类的数据:照一张相片或录一段音) 
ACTION_DIAL                         拨打一个指定的号码,显示一个带有号码的用户界面,允许用户去启动呼叫 
ACTION_CALL                         根据指定的数据执行一次呼叫(ACTION_CALL在应用中启动一次呼叫有缺陷,多数应用ACTION_DIAL,ACTION_CALL不能用在紧急呼叫上,紧急呼叫可以用ACTION_DIAL来实现) 
ACTION_SEND                         传递数据,被传送的数据没有指定,接收的action请求用户发数据 
ACTION_SENDTO                       发送一跳信息到指定的某人 
ACTION_ANSWER                       处理一个打进电话呼叫 
ACTION_INSERT                       插入一条空项目到已给的容器 
ACTION_DELETE                       从容器中删除已给的数据 
ACTION_RUN                          运行数据,无论怎么 
ACTION_SYNC                         同步执行一个数据 
ACTION_PICK_ACTIVITY                为已知的Intent选择一个Activity,返回选中的类 
ACTION_SEARCH                       执行一次搜索 
ACTION_WEB_SEARCH                   执行一次web搜索 
ACTION_FACTORY_TEST                 工场测试的主要进入点, 


标准的广播Actions 
ACTION_TIME_TICK                   当前时间改变,每分钟都发送,不能通过组件声明来接收,只有通过Context.registerReceiver()方法来注册 
ACTION_TIME_CHANGED                时间被设置 
ACTION_TIMEZONE_CHANGED            时间区改变 
ACTION_BOOT_COMPLETED              系统完成启动后,一次广播 
ACTION_PACKAGE_ADDED               一个新应用包已经安装在设备上,数据包括包名(最新安装的包程序不能接收到这个广播) 
ACTION_PACKAGE_CHANGED             一个已存在的应用程序包已经改变,包括包名 
ACTION_PACKAGE_REMOVED             一个已存在的应用程序包已经从设备上移除,包括包名(正在被安装的包程序不能接收到这个广播) 
ACTION_PACKAGE_RESTARTED           用户重新开始一个包,包的所有进程将被杀死,所有与其联系的运行时间状态应该被移除,包括包名(重新开始包程序不能接收到这个广播) 
ACTION_PACKAGE_DATA_CLEARED        用户已经清除一个包的数据,包括包名(清除包程序不能接收到这个广播) 
ACTION_BATTERY_CHANGED             电池的充电状态、电荷级别改变,不能通过组建声明接收这个广播,只有通过Context.registerReceiver()注册 
ACTION_UID_REMOVED     一个用户ID已经从系统中移除

android.intent.action.ALL_APPS
android.intent.action.ANSWER
android.intent.action.ATTACH_DATA
android.intent.action.BUG_REPORT
android.intent.action.CALL
android.intent.action.CALL_BUTTON
android.intent.action.CHOOSER
android.intent.action.CREATE_LIVE_FOLDER
android.intent.action.CREATE_SHORTCUT
android.intent.action.DELETE
android.intent.action.DIAL
android.intent.action.EDIT
android.intent.action.GET_CONTENT
android.intent.action.INSERT
android.intent.action.INSERT_OR_EDIT
android.intent.action.MAIN
android.intent.action.MEDIA_SEARCH
android.intent.action.PICK
android.intent.action.PICK_ACTIVITY
android.intent.action.RINGTONE_PICKER
android.intent.action.RUN
android.intent.action.SEARCH
android.intent.action.SEARCH_LONG_PRESS
android.intent.action.SEND
android.intent.action.SENDTO
android.intent.action.SET_WALLPAPER
android.intent.action.SYNC
android.intent.action.SYSTEM_TUTORIAL
android.intent.action.VIEW
android.intent.action.VOICE_COMMAND
android.intent.action.WEB_SEARCH
android.net.wifi.PICK_WIFI_NETWORK

SETTING:
android.settings.AIRPLANE_MODE_SETTINGS
android.settings.APN_SETTINGS
android.settings.APPLICATION_DEVELOPMENT_SETTINGS
android.settings.APPLICATION_SETTINGS
android.settings.BLUETOOTH_SETTINGS
android.settings.DATA_ROAMING_SETTINGS
android.settings.DATE_SETTINGS
android.settings.DISPLAY_SETTINGS
android.settings.INPUT_METHOD_SETTINGS
android.settings.INTERNAL_STORAGE_SETTINGS
android.settings.LOCALE_SETTINGS
android.settings.LOCATION_SOURCE_SETTINGS
android.settings.MANAGE_APPLICATIONS_SETTINGS
android.settings.MEMORY_CARD_SETTINGS
android.settings.NETWORK_OPERATOR_SETTINGS
android.settings.QUICK_LAUNCH_SETTINGS
android.settings.SECURITY_SETTINGS
android.settings.SETTINGS
android.settings.SOUND_SETTINGS
android.settings.SYNC_SETTINGS
android.settings.USER_DICTIONARY_SETTINGS
android.settings.WIFI_IP_SETTINGS
android.settings.WIFI_SETTINGS
android.settings.WIRELESS_SETTINGS

在android SDK文档中有这样一个类,android.provider.Settings类提供android系统各个页面的跳转常量:
使用实例例:startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)),即可跳到android手机网络设置页面。
如果要launch Mobile Networks Setting页面按如下方法:
Intent intent=new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
ComponentName cName = new ComponentName(“com.android.phone”,com.android.phone.Settings);
intent.setComponent(cName);
startActivity(intent);

如果要进入Networks Operators页面按如下方法:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName(“com.android.phone”,com.android.phone.NetworkSetting);
startActivity(intent);

String ACTION_ACCESSIBILITY_SETTINGS
辅助功能模块的显示设置。 Activity Action: Show settings for accessibility modules.
String ACTION_ADD_ACCOUNT
显示屏幕上创建一个新帐户添加帐户。 Activity Action: Show add account screen for creating a new account.
String ACTION_AIRPLANE_MODE_SETTINGS
显示设置,以允许进入/退出飞行模式。 Activity Action: Show settings to allow entering/exiting airplane mode.
String ACTION_APN_SETTINGS
显示设置,以允许配置的APN。 Activity Action: Show settings to allow configuration of APNs.
String ACTION_APPLICATION_DETAILS_SETTINGS
有关特定应用程序的详细信息的显示屏幕。 Activity Action: Show screen of details about a particular application.
String ACTION_APPLICATION_DEVELOPMENT_SETTINGS
显示设置,以允许应用程序开发相关的设置配置 Activity Action: Show settings to allow configuration of application development-related settings.
String ACTION_APPLICATION_SETTINGS
显示设置,以允许应用程序相关的设置配置 Activity Action: Show settings to allow configuration of application-related settings.
String ACTION_BLUETOOTH_SETTINGS
显示设置,以允许蓝牙配置 Activity Action: Show settings to allow configuration of Bluetooth.
String ACTION_DATA_ROAMING_SETTINGS
选择of2G/3G显示设置 Activity Action: Show settings for selection of2G/3G.
String ACTION_DATE_SETTINGS
显示日期和时间设置,以允许配置 Activity Action: Show settings to allow configuration of date and time.
String ACTION_DEVICE_INFO_SETTINGS
显示一般的设备信息设置(序列号,软件版本,电话号码,等) Activity Action: Show general device information settings (serial number, software version, phone number, etc.).
String ACTION_DISPLAY_SETTINGS
显示设置,以允许配置显示 Activity Action: Show settings to allow configuration of display.
String ACTION_INPUT_METHOD_SETTINGS
特别配置的输入方法,允许用户启用输入法的显示设置 Activity Action: Show settings to configure input methods, in particular allowing the user to enable input methods.
String ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
显示设置来启用/禁用输入法亚型 Activity Action: Show settings to enable/disable input method subtypes.
String ACTION_INTERNAL_STORAGE_SETTINGS
内部存储的显示设置 Activity Action: Show settings for internal storage.
String ACTION_LOCALE_SETTINGS
显示设置,以允许配置的语言环境 Activity Action: Show settings to allow configuration of locale.
String ACTION_LOCATION_SOURCE_SETTINGS
显示设置,以允许当前位置源的配置 Activity Action: Show settings to allow configuration of current location sources.
String ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS
显示设置来管理所有的应用程序 Activity Action: Show settings to manage all applications.
String ACTION_MANAGE_APPLICATIONS_SETTINGS
显示设置来管理安装的应用程序 Activity Action: Show settings to manage installed applications.
String ACTION_MEMORY_CARD_SETTINGS
显示设置为存储卡存储 Activity Action: Show settings for memory card storage.
String ACTION_NETWORK_OPERATOR_SETTINGS
选择网络运营商的显示设置 Activity Action: Show settings for selecting the network operator.
String ACTION_PRIVACY_SETTINGS
显示设置,以允许配置隐私选项 Activity Action: Show settings to allow configuration of privacy options.
String ACTION_QUICK_LAUNCH_SETTINGS
显示设置,以允许快速启动快捷键的配置 Activity Action: Show settings to allow configuration of quick launch shortcuts.
String ACTION_SEARCH_SETTINGS
全局搜索显示设置 Activity Action: Show settings for global search.
String ACTION_SECURITY_SETTINGS
显示设置,以允许配置的安全性和位置隐私 Activity Action: Show settings to allow configuration of security and location privacy.
String ACTION_SETTINGS
显示系统设置 Activity Action: Show system settings.
String ACTION_SOUND_SETTINGS
显示设置,以允许配置声音和音量 Activity Action: Show settings to allow configuration of sound and volume.
String ACTION_SYNC_SETTINGS
显示设置,以允许配置同步设置 Activity Action: Show settings to allow configuration of sync settings.
String ACTION_USER_DICTIONARY_SETTINGS
显示设置来管理用户输入字典 Activity Action: Show settings to manage the user input dictionary.
String ACTION_WIFI_IP_SETTINGS
显示设置,以允许配置一个静态IP地址的WiFi Activity Action: Show settings to allow configuration of a static IP address for Wi-Fi.
String ACTION_WIFI_SETTINGS
显示设置,以允许WiFi配置 Activity Action: Show settings to allow configuration of Wi-Fi.
String ACTION_WIRELESS_SETTINGS
显示设置,以允许配置,如WiFi,蓝牙和移动网络的无线控制 Activity Action: Show settings to allow configuration of wireless controls such as Wi-Fi, Bluetooth and Mobile networks.
String AUTHORITY
String EXTRA_AUTHORITIES
在推出活动的基础上给予的权力限制可选项。 Activity Extra: Limit available options in launched activity based on the given authority.
String EXTRA_INPUT_METHOD_ID
2、显示intent
//AndroidManifest.xml
//要注册一下类才可以启动这个activity
<activity android:name=".MyAty"/>
//创建一个子类绑定layout
public class MyAty extends Activity {
   
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        //绑定layout
        setContentView(R.layout.activity_main);
    }
}
public class MainActivity extends AppCompatActivity {
   
    private Button btn;//声明按钮的变量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=findViewById(R.id.nan_btn);
        btn.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View v) {
   
                btn.setText("按钮点击事件的第一种已经触发~~~");
                //说的很明确了要启动哪个类的activity所以是显示intent
                startActivity(new Intent(MainActivity.this,MyAty.class));
            }
        });
    }
}
3、隐式intent
AndroidManifest.xml
//android:exported=true则其它应用可以访问,如果为false那么其它应用就访问不了了
 <activity android:name=".MyAty"
            android:exported="true">
        //隐式intent是靠遍历合适条件的intent来启动的因此需要过滤器
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                //action 字符串叫什么都可以,可以被找到就行
                <action android:name="com.example.myapplication.intent.action.MyAty"/>
            </intent-filter>
        </activity>
//其它同上
public class MyAty extends Activity {
   
    public static final String ACTION = "com.example.myapplication.intent.action.MyAty";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
btn.setOnClickListener(new View.OnClickListener() {
   
    @Override
    public void onClick(View v) {
   
        btn.setText("按钮点击事件的第一种已经触发~~~");
        //通过manifest里的intent过滤的android name来启动activity,
        //startActivity(new Intent("com.example.myapplication.intent.action.MyAty"));     
        startActivity(new Intent(MyAty.ACTION));
    }
});

4)try-catch的使用以及细节

1、基本语法

try{
   
//可疑代码
//将异常生成对象的异常对象传递给catch块
}catch(异常){
   
//对异常进行处理
}finally{
   
} //可以没有finally

2、语法细节

  1. 如果异常发生了,则异常发生后面的代码不会执行,直接进入到catch
  2. 如果异常没有发生,则顺序执行try的代码块,不会进入到catch
  3. 如果希望发不发生异常都进入到某段代码段 例如:关闭数据库的连接,则使用 finally{ }
public static void main(String[] args) {
   

    //ctrl + alt +t 
    try {
   
        String str = "123";
        int a = Integer.parseInt(str);
        System.out.println(a);
    } catch (NumberFormatException e) {
   //判断数字格式的异常
        System.out.println("异常信息" + e.getMessage());
    }finally {
   
        System.out.println("finally代码块被执行");
    }
    System.out.println("程序继续");
}
*****************************************************************
运行结果为:
123
finally代码被执行
程序继续
*****************************************************************
当更改为"abc"时,语句运行结果为:
异常信息For input string: "abc"
finally代码块被执行
程序继续

3、多个catch语句情况

可以有多个catch语句,捕捉不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,比如Exception 在后 ,NullPointerException在前,如果发生异常,只会匹配一个catch

public class TryCatchDetai {
   
    public static void main(String[] args) {
   

        try {
   
            Person person = new Person();
            person = null;
            System.out.println(person.getName());
            int n1 = 10;
            int n2 = 0;
            int res = n1/n2;
        }catch (NullPointerException e){
   
            System.out.println("空指针异常 " + e.getMessage());
        }
        catch (Exception e){
   		//Exception e为任意异常
            System.out.println("算术异常" + e.getMessage());
        }finally {
   

        }
    }
}

class Person{
   
    private String name = "yayaya";

    public String getName(){
   
        return name;
    }
}
****************************************************
运行的结果为:
空指针异常:null
但是实际上还有一个异常为算术异常 及分母不能为0,因为已经找到一个异常就不会捕获下一个异常。
如果更改获取异常的顺序,编译器就会报错。所以父类异常需要在后,子类异常需要在前。

5)Handler消息机制

1、应用程序启动的时候,在主线程会默认调用了LOOPER.preper()方法,初始化Looper对象并绑定到当前线程中,并在LOOPER内部维护一个MessageQueue。

2、接着调用handler.sendMessage()发送消息,会通过MessageQueue.enqueueMessage()向MessageQueue中添加一条消息。

3、主线程调用LOOPER.kooper()开启循环,不断轮询消息队列,通过MessageQueue.next()取出消息。

4、取出的message部位空则调用msg.target.dispatchMessage()传递分发消息,目标handler收到消息后会执行handler.handlerMessage()方法处理消息。


子线程:handler.sendMessage(msg)
主线程:handler.handleMessage(msg)

5、looper对象

一个looper对应一个handler再对应一个messageQueue。

安卓中如果在子线程中对UI进行更改则会抛出警告,这个时候就要用handler。

looper对象用于对一个线程开启消息循环。新创建的子线程是没有looper对象的,主线程除外。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-je6EWFoD-1680608690283)(图库/android底层开发9.png)]

Looper创建线程过程

import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.os.Handler;

public class LooperThread extends Thread{
   
    public Handler handler1; //声明一个Handler对象

    @Override
    public void run() {
   
        super.run();
        Looper.prepare(); //初始化looper对象

        handler1 = new Handler(){
   
            @Override
            public void handleMessage(Message msg) {
   
                Log.i("Looper",String.valueOf(msg.what));
            }
        };

        Message m = handler1.obtainMessage();//获取一个消息
        m.what = 0x11; //设置Message的what属性值的值
        handler1.sendMessage(m);
        Looper.loop();
    }
}
public class MainActivity extends Activity {
   

    private Thread thread;
    private static MediaPlayer mp = null;//声明一个播放器对象
    int i;//循环变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LooperThread thread = new LooperThread(); //创建线程
        thread.start();// 开启线程
    }
}
//logcat
2022-11-13 22:21:13.749 10983-11028/com.example.myapplication I/Looper: 17

6、Handler类

Handler类用于子线程与主线程之间的通讯。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2UAkECgD-1680608690286)(图库/android底层开发10.png)]

7、Message类

Message存放在消息队列中。Message类的使用方式比较简单,有几点:

  • 通常使用message.obtain()或handler.message方法来从消息池中获取空消息对象以节省资源
  • 如果一个message只需要获取简单的整形信息,因优先使用arg1、arg2来传递消息
  • 尽可能用msg.what来标记信息
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PHestJYO-1680608690288)(图库/android底层开发11.png)]

例:获取网络图片参数为URI

public class MainActivity extends Activity {
   

    private ImageView iv; //声明ImageView组件的对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.imagView1);// 获取布局管理器中添加的imageView

        new Thread(new Runnable() {
   
            @Override
            public void run() {
   
                final Bitmap bitmap = getPicture("https://pics4.baidu.com/feed/3b292df5e0fe99252bd6683eba2d1ed48cb17112.jpeg@f_auto?token=899cd1cfd0f29ba5b566d76a6c8eb742"); //网络上获取资源
                try {
   
                    Thread.sleep(2000);     //线程休眠2秒
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
                //发送一个Runnable对象
                iv.post(new Runnable() {
   
                    @Override
                    public void run() {
   
                        iv.setImageBitmap(bitmap); //在imageView中显示从网络上获取到的图片
                    }
                });
            }
        }).start();//开启线程
    }

    /**
     * 功能:根据网址获取图片对应的Bitmap对象
     *
     * @param path
     * @return
     */
    public Bitmap getPicture(Stri
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值