android-浏览器拉起app
android-浏览器拉起app
前篇
- Android 利用scheme协议进行跳转 - https://www.jianshu.com/p/f9f9f0aa0f86
- android:如何跳回指定的已存在的activity界面 - http://www.heycode.com/a8013.html
需求是: app 打开浏览器, 浏览器进行一系列操作之后, 重定向拉起 app, 并把相关浏览器网页相关数据传递到 app 中
实现结果:

步骤
- 新创建一个 activity, 通过 scheme 协议被 浏览器拉起 - 创建 activity - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20- public class TempActivity extends AppCompatActivity { 
 
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 // 浏览器通过 scheme 传递过来的数据
 Uri uri = getIntent().getData();
 if (uri != null)
 LogUtil.D("--- uri 222, host = " + uri.getHost() + " path = " + uri.getPath() + " query = " + uri.getQuery());
 // 拉起主 activity
 Intent intent = new Intent(TempActivity.this, PageMain.class); // PageMain 是主 activity
 intent.setData(uri);
 startActivity(intent);
 
 // 结束当前 activity
 finish();
 }
 }
- AndroidManifest.xml 配置这个 activity - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29- <activity 
 android:name=".TempActivity"
 android:exported="true">
 <!-- 协议 scheme -->
 <intent-filter>
 <!-- 下面这几行也必须得设置 -->
 <action android:name="android.intent.action.VIEW" />
 <category android:name="android.intent.category.DEFAULT" />
 <category android:name="android.intent.category.BROWSABLE" />
 
 <data
 android:host="world01"
 android:path="/wolegequ01"
 android:scheme="hello01" />
 </intent-filter>
 </activity>
 2. 主 activity 配置
 1. AndroidManifest.xml 配置这个 主 activity 的 *launchMode* 为 *singleTask* (*单任务模式*)
 因为单任务模式下, 其他 activity 通过 startActivity 跳转到这个 主 activity 时, 才不会重新创建一个 主 activity (可以理解为单例模式)
 ```xml
 <activity
 android:name=".page.PageMain"
 android:launchMode="singleTask" // 单任务模式
 android:exported="true"
 </activity>
- 获取 TempActivity 跳转到 PageMain 的参数 - ```java 
 public class PageMain extends AppCompatActivity {- @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Uri uri = intent.getData(); if (uri != null) { PageMain.log("--- uri 444, host = " + uri.getHost() + " path = " + uri.getPath() + " query = " + uri.getQuery()); } getIntent().setData(uri); // startActivity 传递过来的数据存起来, onResume 获取到后拿来使用. 也可以起个成员变量用来存取数据 } @Override protected void onResume() { super.onResume(); Uri uri = getIntent().getData(); if (uri != null) { PageMain.log("--- uri 555, host = " + uri.getHost() + " path = " + uri.getPath() + " query = " + uri.getQuery()); } }- }