我想在公开场合记录这些知识,以便其他人(包括我自己)可以在以后找到它。
答案 0 :(得分:1)
如果您在WebView
中使用自己的网页,那么这可以是解决方案:
<强> MainActivity.java 强>
public class MainActivity extends ActionBarActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webView1);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.loadUrl("file:///android_asset/index.html");
}
public class WebAppInterface {
Context mContext;
public WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void openMyApp() {
PackageManager pManager = getPackageManager();
// here you should use a package name of the application
// you want to open
Intent launchIntent = pManager.getLaunchIntentForPackage("com.android.mms");
startActivity(launchIntent);
}
}
}
<强> activity_main.xml中强>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<强>资产/ index.html中强>
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body style="text-align: center;">
<script type="text/javascript">
function openApp() {
Android.openMyApp();
}
</script>
<h1>Open app test</h1>
<button type="button" onclick="openApp()">Click Me!</button>
</body>
答案 1 :(得分:1)
使用Android标准
您应该为此目的使用自定义链接和intent-filter:
将href设置为
进行链接android-app://com.example.android/http/example.com/gizmos?1234
应用程序清单文件中的将intent-filter声明为
<activity
android:name=".MainActivity"
android:label="MyApp"
android:screenOrientation="portrait" >
<intent-filter>
<data android:scheme="android-app"
android:host="com.example.android" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
主活动中的将传入的意图处理为:
//required only if you want to get some params from url
Intent intent = getIntent();
Uri data = intent.getData();
如果应用安装在设备上,则会打开应用的MainActivity,否则会将用户带到example.com。
参考文献:
https://developer.android.com/training/app-indexing/deep-linking.html https://developers.google.com/app-indexing/webmasters/server