Android開発における主要な知識ポイント

Intentの基本的使用法

ブラウザ起動の例:

Uri webUri = Uri.parse("https://example.com");
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, webUri);
startActivity(launchBrowser);

アクティビティ遷移の例:

Intent nextActivity = new Intent();
nextActivity.setClass(CurrentActivity.this, TargetActivity.class);
startActivity(nextActivity);

アクティビティ間データ連携

データ送信:

Intent transferData = new Intent();
Bundle userData = new Bundle();
userData.putString("USER_NAME", inputName.getText().toString());
userData.putString("USER_AGE", inputAge.getText().toString());
transferData.putExtras(userData);
transferData.setClass(SourceActivity.this, DestinationActivity.class);
startActivity(transferData);

データ受信:

Bundle receivedBundle = getIntent().getExtras();
String userName = receivedBundle.getString("USER_NAME");

結果取得付きアクティビティ起動

リクエスト送信:

final int REQUEST_CODE = 100;
Intent resultRequest = new Intent(Source.this, Target.class);
startActivityForResult(resultRequest, REQUEST_CODE);

結果処理:

@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
  super.onActivityResult(reqCode, resCode, data);
  if (reqCode == REQUEST_CODE) {
    if (resCode == RESULT_OK) {
      Bundle result = data.getExtras();
      String info = result.getString("RESULT_DATA");
      // 結果を使用した処理
    }
  }
}

結果返却:

Intent returnData = new Intent();
Bundle resultBundle = new Bundle();
resultBundle.putString("RESULT_DATA", processedValue);
returnData.putExtras(resultBundle);
setResult(RESULT_OK, returnData);
finish();

サービスによる音楽再生

マニフェスト定義:

<service android:name=".AudioService">
  <intent-filter>
    <action android:name="com.example.service.AUDIO_PLAYER"/>
  </intent-filter>
</service>

サービス実装:

public void onStart(Intent intent, int startId) {
  super.onStart(intent, startId);
  audioPlayer = MediaPlayer.create(this, R.raw.sample_audio);
  audioPlayer.start();
}

public void onDestroy() {
  super.onDestroy();
  audioPlayer.stop();
}

サービス制御:

startService(new Intent("com.example.service.AUDIO_PLAYER"));
stopService(new Intent("com.example.service.AUDIO_PLAYER"));

UI操作技法

画面情報取得:

DisplayMetrics displayInfo = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayInfo);

フルスクリーン設定:

requestWindowFeature(Window.FEATURE_NO_TITLE);
int fullscreenFlag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
Window appWindow = getWindow();
appWindow.setFlags(fullscreenFlag, fullscreenFlag);

ボタン処理:

buttonElement.setOnClickListener(v -> {
  // クリック時の処理
});

Toast通知:

Toast imageToast = new Toast(this);
ImageView toastImage = new ImageView(this);
toastImage.setImageResource(R.drawable.notification_icon);
imageToast.setView(toastImage);
imageToast.setDuration(Toast.LENGTH_LONG);
imageToast.show();

エミュレータデバッグ

Socket debugSocket = new Socket("10.0.2.2", 8080);

タグ: Android Intent Activity service Bundle

7月25日 21:29 投稿