0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AndroidのWebViewでAngularからアプリへデータを渡す

Posted at

AndroidのWebViewでAngularで作成したWebページからアプリへデータを渡す

  • Angular側のソース

以下を宣言する

top.component.ts
declare global {
  interface Window {
    android: any;
  }
}

アプリへデータを渡す箇所(抜粋)

top.component.ts
let model : TicketModel = new TicketModel();
model.id = "00001";
model.name = "テスト";
let jsonStr : string = JSON.stringify(model);
window.android.showMessage(jsonStr);

TicketModelクラスは以下の通り

ticket.model.ts
export class TicketModel {
  id? : string;
  name? : string;
}
  • Android側のソース
     (activiti_main.xmlにWebViewを定義し、idをwebViewとしているものとする)
MainActivity.kt
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val webView :WebView = findViewById(R.id.webView)
    webView.setWebViewClient(WebViewClient());
    webView.getSettings().javaScriptEnabled = true;
    webView.getSettings().allowFileAccess = true;

    //http://localhostにアクセスできるよう設定
    WebView.setWebContentsDebuggingEnabled(true);

    val webAppInterface = WebAppInterface(this@MainActivity)
    webView.addJavascriptInterface(webAppInterface, "android");

    //localhostで起動したAngularを表示する
    webView.loadUrl("http://localhost:4200")
  }
}

Angularからのデータを受け取る

WebAppInterface.kt
class WebAppInterface(private val context:Context) {
  @JavascriptInterface
  fun showMessage(message:String):String {
    //JSON形式の文字列で受けてデコードする
    val model:TicketModel = Json.decodeFromString<TicketModel>(message)

    //受け取ったデータをToastで表示
    Toast.makeText(context, model.id + ":" + model.name, Toast.LENGTH_LONG).show();
    return message;
  }
}

TicketModelクラスは以下の通り

TicketModel.kt
@Serializable
data class TicketModel(
    val id:String = "",
    val name:String = ""
)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?