本文模擬的是appA喚起appB,打開指定的BActivity頁面的情況,兩個應用的頁面結構如下圖所示:
瀏覽器或者其它應用,通過scheme配置喚起目標應用,需要約定的uri,如示例代碼中的
String uri = "appb://com.windfallsheng.myapplicationb/sign?type=1&targetPage=BActivity&userName=windfallsheng";
在appA中只需要根據
package com.windfallsheng.myapplicationa;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void launchAPPB(View view) {
String uri = "appb://com.windfallsheng.myapplicationb/sign?type=1&targetPage=BActivity&userName=windfallsheng";
Intent intent = new Intent();
intent.setData(Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:textSize="35sp"
android:background="@drawable/selector_item_background"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintVertical_bias="0.5"
app:layout_constraintWidth_percent="0.7"
app:layout_constraintHeight_percent="0.15"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="喚起B應用"
android:onClick="launchAPPB"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
在appB的攔截頁面配置:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.windfallsheng.myapplicationb">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<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:scheme="appb" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:launchMode="singleTask"></activity>
<activity android:name=".BActivity"></activity>
<activity android:name=".CActivity"></activity>
</application>
</manifest>
package com.windfallsheng.myapplicationb;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class WelcomeActivity extends AppCompatActivity {
CodeReqCountDownTimer codeReqCountDownTimer;
String type;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("appB", "WelcomeActivity#onNewIntent");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
Uri data = getIntent().getData();
Log.d("appB", "WelcomeActivity#onCreate#data=" + data);
if (data != null) {
String userName = data.getQueryParameter("userName");
String targetPage = data.getQueryParameter("targetPage");
type = data.getQueryParameter("type");
Log.d("appB", "WelcomeActivity#onCreate#type=" + type + ", targetPage=" + targetPage + ", userName=" + userName);
}
TextView tv = findViewById(R.id.textView);
codeReqCountDownTimer = new CodeReqCountDownTimer(tv, 4 * 1000, 1000);
codeReqCountDownTimer.start();
}
/**
* 時間倒計時
*/
class CodeReqCountDownTimer extends CountDownTimer {
private TextView tv;
public CodeReqCountDownTimer(TextView textView, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.tv = textView;
}
@Override
public void onTick(long l) {
String timeStr = l / 1000 + "s";
tv.setText(timeStr); //設置倒計時時間
}
@Override
public void onFinish() {
if (TextUtils.equals("1", type)) {
tv.setText("即將進入B頁面");
} else {
tv.setText("即將進入主頁");
}
new Handler().postDelayed(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (TextUtils.equals("1", type)) { // 經scheme喚起應用;
startActivity(new Intent(WelcomeActivity.this, BActivity.class));
} else {// 正常啓動應用;
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
}
WelcomeActivity.this.finish();
}
}, 1000);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
codeReqCountDownTimer.cancel();
codeReqCountDownTimer = null;
}
}
目前的配置是可以實現目標應用appB被喚起,但是有一個問題,如果appB是在被首次喚醒啓動後再次喚起,或者appB是被桌面圖標首先啓動,則攔截界面不會啓動;
正常的業務需求應該是每次從瀏覽器喚起應用後,都會經過應用啓動頁,之後再跳轉向目標分享頁面,同時應用如果在後臺運行,則不會重啓應用,正如下面圖中演示的情況;
appA首次喚起appB的情況,如下圖:
appA首次喚起appB後,再多次喚起的情況,如下圖:
要解決一開始的問題,實現這樣的業務情況,需要在喚起的應用B中做處理:
將應用B的攔截頁面的Activity啓動模式改爲 :
android:launchMode="singleTask"
其它的啓動模式是無效的。
解決應用被三方喚起後,再通過桌面圖標啓動,會引起應用重啓的問題的解決方法是在啓動頁加入如下的代碼:
if (!this.isTaskRoot()) { Intent intent = getIntent(); if (intent != null) { String action = intent.getAction(); if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) { Log.d("appB", "WelcomeActivity#onCreate#finish"); finish(); } } }
完整的代碼示例如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.windfallsheng.myapplicationb">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".WelcomeActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<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:scheme="appb" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:launchMode="singleTask"></activity>
<activity android:name=".BActivity"></activity>
<activity android:name=".CActivity"></activity>
</application>
</manifest>
package com.windfallsheng.myapplicationb;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import java.util.List;
import androidx.appcompat.app.AppCompatActivity;
public class WelcomeActivity extends AppCompatActivity {
CodeReqCountDownTimer codeReqCountDownTimer;
String type;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("appB", "WelcomeActivity#onNewIntent");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
if (!this.isTaskRoot()) {
Intent intent = getIntent();
if (intent != null) {
String action = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
Log.d("appB", "WelcomeActivity#onCreate#finish");
finish();
}
}
}
Uri data = getIntent().getData();
Log.d("appB", "WelcomeActivity#onCreate#data=" + data);
if (data != null) {
String userName = data.getQueryParameter("userName");
String targetPage = data.getQueryParameter("targetPage");
type = data.getQueryParameter("type");
Log.d("appB", "WelcomeActivity#onCreate#type=" + type + ", targetPage=" + targetPage+", userName=" + userName);
}
TextView tv = findViewById(R.id.textView);
codeReqCountDownTimer = new CodeReqCountDownTimer(tv, 4 * 1000, 1000);
codeReqCountDownTimer.start();
}
/**
* 時間倒計時
*/
class CodeReqCountDownTimer extends CountDownTimer {
private TextView tv;
public CodeReqCountDownTimer(TextView textView, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.tv = textView;
}
@Override
public void onTick(long l) {
String timeStr = l / 1000 + "s";
tv.setText(timeStr); //設置倒計時時間
}
@Override
public void onFinish() {
if (TextUtils.equals("1", type)) {
tv.setText("即將進入B頁面");
} else {
tv.setText("即將進入主頁");
}
new Handler().postDelayed(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (TextUtils.equals("1", type)) { // 經scheme喚起應用;
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//獲取activity任務棧,獲取任務棧列表
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
tasks.stream().forEach(task -> {
ActivityManager.RecentTaskInfo info = task.getTaskInfo();
// int taskId = info.taskId;
int activityCount = info.numActivities; //棧內Activity數量
String topActivity = info.topActivity.getClassName(); //棧頂Activity
String baseActivity = info.baseActivity.getClassName(); //棧底Activity
Log.d("appB", "WelcomeActivity#activityCount=" + activityCount + ", topActivity=" + topActivity + ", baseActivity=" + baseActivity);
});
if (tasks.size() == 1) {
int activityCount = tasks.get(0).getTaskInfo().numActivities;
Log.d("appB", "WelcomeActivity#activityCount=" + activityCount);
if (activityCount > 1) {// 目標應用已經被喚起的情況;
startActivity(new Intent(WelcomeActivity.this, BActivity.class));
} else { // 目標應用首次被喚起的情況;
Intent mainIntent = new Intent(WelcomeActivity.this, MainActivity.class);
Intent bIntent = new Intent(WelcomeActivity.this, BActivity.class);
//注意此處的順序
startActivities(new Intent[]{mainIntent, bIntent});
}
} else {// 目標應用已經被喚起的情況;
startActivity(new Intent(WelcomeActivity.this, BActivity.class));
}
} else {// 正常啓動應用;
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
}
WelcomeActivity.this.finish();
}
}, 1000);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
codeReqCountDownTimer.cancel();
codeReqCountDownTimer = null;
}
}
啓動頁中的:
startActivities(new Intent[]{mainIntent, bIntent});
這個方法是爲了解決瀏覽器首次喚起應用後,直接打開了目標分享頁面,用戶返回時沒有返回到B應用的主頁問題。
package com.windfallsheng.myapplicationb;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@SuppressLint("NewApi")
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("appB", "MainActivity#onNewIntent");
// 獲取activity任務棧
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//獲取任務棧列表
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
tasks.stream().forEach(task -> {
ActivityManager.RecentTaskInfo info = task.getTaskInfo();
// int taskId = info.taskId;
int activityCount = info.numActivities; //棧內Activity數量
String topActivity = info.topActivity.getClassName(); //棧頂Activity
String baseActivity = info.baseActivity.getClassName(); //棧底Activity
Log.d("appB", "MainActivity#onNewIntent#activityCount=" + activityCount + ", topActivity=" + topActivity + ", baseActivity=" + baseActivity);
});
}
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("appB", "MainActivity#onCreate");
// 獲取activity任務棧
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//獲取任務棧列表
List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
tasks.stream().forEach(task -> {
ActivityManager.RecentTaskInfo info = task.getTaskInfo();
// int taskId = info.taskId;
int activityCount = info.numActivities; //棧內Activity數量
String topActivity = info.topActivity.getClassName(); //棧頂Activity
String baseActivity = info.baseActivity.getClassName(); //棧底Activity
Log.d("appB", "MainActivity#onCreate#activityCount=" + activityCount + ", topActivity=" + topActivity + ", baseActivity=" + baseActivity);
});
}
public void goToPageB(View view) {
startActivity(new Intent(this, BActivity.class));
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/selector_item_background"
android:gravity="center"
android:onClick="goToPageB"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="打開B頁面"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5"
app:layout_constraintWidth_percent="0.7" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="62dp"
android:text="Main_Activity"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.windfallsheng.myapplicationb;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class BActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
Log.d("appB", "BActivity#onCreate");
}
public void goToPageC(View view) {
startActivity(new Intent(this, CActivity.class));
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
tools:context=".BActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/selector_item_background"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintVertical_bias="0.5"
app:layout_constraintWidth_percent="0.7"
app:layout_constraintHeight_percent="0.15"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:onClick="goToPageC"
android:gravity="center"
android:text="打開C頁面"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="62dp"
android:text="B_Activity"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.windfallsheng.myapplicationb;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class CActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c);
Log.d("appB", "CActivity#onCreate");
}
public void goToPageMain(View view) {
startActivity(new Intent(this, MainActivity.class));
}
public void goToPageB(View view) {
startActivity(new Intent(this, BActivity.class));
}
public void goToPageWelcome(View view) {
startActivity(new Intent(this, WelcomeActivity.class));
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
tools:context=".CActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="36dp"
android:background="@drawable/selector_item_background"
android:gravity="center"
android:onClick="goToPageMain"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="打開Main頁面"
android:textSize="35sp"
app:layout_constraintBottom_toTopOf="@+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintWidth_percent="0.7" />
<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="37dp"
android:background="@drawable/selector_item_background"
android:gravity="center"
android:onClick="goToPageB"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="打開B頁面"
android:textSize="35sp"
app:layout_constraintBottom_toTopOf="@+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintWidth_percent="0.7" />
<TextView
android:id="@+id/textView4"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="59dp"
android:background="@drawable/selector_item_background"
android:gravity="center"
android:onClick="goToPageWelcome"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="打開Welcome頁面"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3"
app:layout_constraintWidth_percent="0.7" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="62dp"
android:layout_marginBottom="58dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="C_Activity"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.7" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_checked" android:state_checked="true"/>
<item android:drawable="@drawable/shape_checked" android:state_selected="true"/>
<item android:drawable="@drawable/shape_checked" android:state_focused="true"/>
<item android:drawable="@drawable/shape_normal" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp"></corners>
<solid android:color="#F6F6F6" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp"></corners>
<solid android:color="#FFF" />
</shape>
由於作者水平有限,語言描述及代碼實現中難免有紕漏,望各位看官多提寶貴意見!
Hello , World !
感謝所有!