約 5,434,926 件
https://w.atwiki.jp/bagpack/pages/15.html
Google Android プログラミング入門メモ Activityの作成 手順1 新しいリソースの定義(string.xmlとlayout/hogehoge.xml) 新しいActivityクラスのコーディング 新たに作成したActivityクラスをマニフェストファイルに追記 Activity間でのデータの受け渡しはintentでも使えばおk SharedPreference データの共有ができる。引数で共有する範囲を設定することもできる。 共有データのセット SharedPreferences preferences = getSharedPreferences("SHARED_NAME", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("SHARED_DATA", shared_data); editor.commit(); setResult(RESULT_OK); finish(); 共有データの読み込み SharedPreferences preferences = getSharedPreferences("SHARED_NAME", MODE_PRIVATE); String shared_data = preferences.getString("SHARED_DATA", 0); // shared_dataがstring型なら BroadcastReceiver ブロードキャストされたインテントに反応する仕組み。 次のようにして作成する。 レシーバクラスの作成 public class MyIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); ... } } マニフェストファイルの定義 ここでレシーバの登録や、インテントフィルタの定義を行う。 アクション名のプリフィックスには、パッケージ名をいれることが推奨されている(気がする)。 receiver android name=".MyIntentReceiver" intent-filter action android name="packagename.intent.action.ACTION_NAME" / category android name="packagename.intent.category.CATEGORY_NAME" / /intent-filter /receiver ブロードキャスト送信する方 Intent intent = new Intent("packagename.intent.action.ACTION_NAME"); ... intent.putExtra("DATANAME", data); sendBroadcaset(intent);
https://w.atwiki.jp/anddoid/pages/63.html
activity 関連タグ 使用例 activity android name=".StartActivity" android label="@string/app_name" intent-filter action / category / /intent-filter /activity activity android name=".MainActivity" /activity
https://w.atwiki.jp/android-reference/pages/23.html
public class Activity since API Level 1 extends ContextThemeWrapper implements ComponentCallbacks KeyEvent.Callback Layoutlnflater.Factory View.OnCreateContextMenuListener Window.Callback java.lang.Object ↳ android.content.Context ↳ android.content.ContextWrapper ↳ android.view.ContextThemeWrapper ↳ android.app.Activity Known Direct Subclasses ActivityGroup, AliasActivity, ExpandableListActivity, ListActivity Known Indirect Subclasses LauncherActivity, PreferenceActivity, TabActivity Class Overview An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically. onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data). To be of use with Context.startActivity(), all activity classes must have a corresponding activity declaration in their package s AndroidManifest.xml. The Activity class is an important part of an application s overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform s application model. For a detailed perspective on the structure of Android applications and lifecycles, please read the Dev Guide document on Application Fundamentals.
https://w.atwiki.jp/conn/pages/18.html
Androidプロジェクト Androidプロジェクトの中身を簡単にまとめます。 ネタ元はAndroid SDKのドキュメントと、EclipseのAndroid SDK Pluginで自動生成された雛形の動作検証です。 プロジェクトのディレクトリ構成 Androidアプリを作るなら、ごく当たり前の知識として知っておく必要があります。 プロジェクトルート src ソースコード用ディレクトリ gen ADTが自動生成したファイル用ディレクトリ。R.javaやAIDLファイルから生成されたファイルが該当。 assets 生のデータファイルを保存する。ビルド時にapkファイルへ組み入れられ、ファイルシステムと変わりない方法でアクセスできる。 bin ビルドされたファイル用ディレクトリres ビルドされたリソースファイル用ディレクトリ libs ライブラリファイル用ディレクトリ res リソースファイル用ディレクトリdrawable-**** 画像ファイルや、レイヤー定義などを記載した描画用定義XMLファイルを保存する。画面解像度ごとにディレクトリが分かれているモヨウ。 layout レイアウト定義XMLファイル用ディレクトリ menu メニュー定義XMLファイル用ディレクトリ values 文字列や設定情報等用のディレクトリ。resディレクトリ内の他のXMLファイルはファイル名ベースでアクセスするのに対し、XML要素を解析し、それぞれの要素名をR.javaファイルに展開しアクセスする点に違いがある。 raw 生のデータファイルを保存する。assetsディレクトリとの違いはアクセス方法で、こちらはR.javaファイルを通じてリソースファイルとしてアクセスする。 AndroidManufest.xml アプリの基本情報を定義する。アプリバージョン、製作者、対応・必要APIバージョン、必要な外部ライブラリなどなど、様々な情報を定義する。奥が深い。 リソースファイル用ディレクトリと、マニフェストファイルは、特に勉強が必要。 詳細が知りたければSDK Managerでドキュメントをインストールし読んでみると良い、全部英語だけども。 雛形プロジェクトの動作 ADTでプロジェクトを作成すると、HelloWorldが表示される簡単なアプリが出来上がった状態になっている。 その動作の細かな点をつついて、それぞれのディレクトリに格納されたファイルが どのように連携するかを調べてみた。 AndroidManifest.xmlを解析しアプリを起動、アクティビティの定義を読み込む。 XMLファイル中では「@」を用いることでリソースにアクセスすることができ、アプリケーション名やスタイル定義の指定に使用されている。 application android icon="@drawable/ic_launcher" <<<res/drawable-****/ic_launcher.pngファイルを参照 android label="@string/app_name" <<<res/valus/strings.xml内の文字列を参照 android theme="@style/AppTheme" <<<res/valus/style.xml内の定義を参照 activity android name=".MainActivity" <<<ここで起動するアクティビティを指定 android label="@string/title_activity_main" <<<res/valus/strings.xml内の文字列を参照 intent-filter action android name="android.intent.action.MAIN" / category android name="android.intent.category.LAUNCHER" / /intent-filter /activity /application binディレクトリ内のデフォルトアクティビティを起動する。 public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); <<<レイアウト定義ファイルを指定 } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); <<<メニュー定義ファイルを指定 return true; } } レイアウト定義ファイル res/layout/activity_main.xml メニュー定義ファイル res/menu/activity_main.xml Activityの動作に従い読み込まれる。 それぞれの定義ファイルにはリソースへのアクセスが指定されている。 TextView android layout_width="wrap_content" android layout_height="wrap_content" android layout_centerHorizontal="true" android layout_centerVertical="true" android text="@string/hello_world" tools context=".MainActivity" / menu xmlns android="http //schemas.android.com/apk/res/android" item android id="@+id/menu_settings" android title="@string/menu_settings" android orderInCategory="100" android showAsAction="never" / /menu 以上が簡単な動作解説です。 マニフェストファイルが起点となり、アクティビティが実際の動作を担っており、 動作時に様々な箇所でリソース内の定義ファイルが読み込まれているのが分かる。 Webアプリケーションなどに比べると非常に単純な構成となっているが、アプリが大きくなるとファイルが増え、管理が難しくなりがち。だがディレクトリ構成の原則に従いアプリを作成することで、誰にでも分かりやすい、無論のこと自分自身にも分かりやすい管理しやすい構成にできる。
https://w.atwiki.jp/memo_android/pages/23.html
Intentを使ってファイルを別アプリで開く 画像、動画、音楽などのファイルを別アプリで開く。 Intentにアクションタイプを指定、アクティビティへIntentを渡す。 設定するパスは、パスからUriタイプへ変換すること。 例1:PDFファイルを開く場合 //インテントを投げる Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file //" + mUrl[i]),"application/pdf"); startActivity(intent); 例2:画像ファイルを開く //インテントを投げる Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(new File(mUrl[i])); intent.setDataAndType(uri, "image/*"); startActivity(intent); 例3:動画ファイルを開く(.mp4) Uri uri = Uri.fromFile(new File(mUrl[i])); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.setDataAndType(uri, "video/mp4"); startActivity(intent); 別のアクティビティへ画面遷移する 任意の異なるアクティビティへ画面遷移させる。 Intentに、Contextと遷移後のActivityクラス名を設定。 例1:単純な画面遷移 現在のActivityをACTIVE_ACTIVITY 遷移先のActivityをNEXT_ACTIVITY とすると以下。 //次のアクティビティへ渡す Intent intent = new Intent(ACTIVE_ACTIVITY.this, NEXT_ACTIVITY.class); //画面遷移 startActivity(intent); 例2:画面間でのデータのやり取りを含めた遷移 引数を渡す 文字列データをSTRING_DATA、文字列データの固有コード(任意)をSTRING_CODE 整数データをINT_DATA、整数データの固有コード(任意)をINT_CODE とすると以下。 送り側 遷移先のActivityへストリングデータとイントデータを渡す //次のアクティビティへ渡す Intent intent = new Intent(ACTIVE_ACTIVITY.this, NEXT_ACTIVITY.class); intent.putExtra("STRING_CODE", STRING_DATA); intent.putExtra("INT_CODE", INT_DATA); //画面遷移 startActivity(intent); 受け側 onCreateでインテントの値を取得する //インテント取得 Intent intent = getIntent(); //文字列の取得 CharSequence string = intent.getCharSequenceExtra("STRING_CODE"); //整数の取得 デフォルト値6 int Number = intent.getIntExtra("INT_CODE", 6); 例3:画面間でのデータのやり取りを含めた遷移 戻り値を取得する 画面遷移時に、startActivityForResultで画面遷移する。 //戻り値ありで次のアクティビティへ遷移 startActivityForResult(intent, SUB_ACTIVITY_CODE); 遷移先のアクティビティ終了時に結果を戻す Intent intent = new Intent(); intent.putExtra("MODE", "GO_HOME"); setResult(SUB_ACTIVITY_CODE, intent); finish(); 結果の受け取り方 onActivityResultでIntentから戻り値を取得する ⇒ファイルの選択などで使用。パスを取得する。 public void onActivityResult(int requestCode, int resultCode, Intent intent) { //サブアクティビティから戻り if(requestCode == SUB_ACTIVITY_CODE) { //値の取得 String mode = intent.getExtras().getString("MODE"); } } 別アプリでファイルのパスを取得する 例:画像ファイルのパスをギャラリーなどのビューアプリを使って取得する。 Intent intent = new Intent(); //初期パスの指定・・・だけどできない様子 Uri uri = Uri.fromFile(new File("/DCIM")); intent.setDataAndType(uri, "image/jpeg"); //↓戻り値付きで画面遷移 intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 0); アプリからの戻りをonActivityResultで取得する @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ //ギャラリーの起動 if(requestCode == 0 resultCode == RESULT_OK){ try{ //パスの取得 ContentResolver cr = getContentResolver(); String[] columns = {MediaColumns.DATA}; Cursor c = cr.query(data.getData(), columns, null, null, null); c.moveToFirst(); String file_path = c.getString(0); }catch(Exception e){ } } }
https://w.atwiki.jp/conn/pages/21.html
このページは現在作成中です Androidアプリの基本構成 Androidアプリは幾つかのコンポーネントを組み合わせて作成する。コンポーネントはその役割ごとに幾つかに分類される。 Androidアプリを構成する4つのコンポーネント もっとも基本的なコンポートネントは次の4種類。 Activities 画面。アクティビティはそれぞれが独立したコンポーネントとして作成され、その組み合わせでアプリを動作させる。別のアプリから、また別のアプリ内のアクティビティを動作させることも可能。 Services 裏側でこっそり働く子。ユーザーインターフェースは持たない。ネットワークからデータをダウンロードしてきたり、別のアプリを操作中に音楽ファイルを再生したり、ユーザーの操作を邪魔することは無い。アクティビティのような他のコンポーネントから起動され、動作を指定される、サービス精神の塊のような存在。 Content Providers アプリケーションのデータへのアクセス共有を管理しデータの読み書きを行う。ファイルシステムやSQLiteなどのDB、インターネット上のデータなど、さまざまな場所に対応する。許可すれば他のアプリからデータの読み書きが可能だし、その逆も可能。動画を配信してくれる業者ではない。 Broadcast Reciever システムからの通知を受け取ったり、システム全体へ通知を発信したりする。例えばスリープに入った、バッテリーが切れ掛かっている、写真を撮った、などなどの通知を受けたり、発信したりできる。 電話を自動録音するアプリなんかだと、電話が掛かってきたという通知を受けサービスを起動し録音する、という使い方が想定される。 他にもコンポーネントには分類されないが、Androidアプリを構成する重要な要素がある。 マニフェスト アプリに属するコンポーネントを規定するのがマニフェストファイル。XML形式で記述する。 Intentフィルターで、アプリのエントリポイント(初期起動するアクティビティ)を指定する。 例:雛形アプリの AndroidManifest.xml。Intentフィルターが Activityの子要素で指定されている。 activity android name=".MainActivity" android label="@string/title_activity_main" intent-filter action android name="android.intent.action.MAIN" / category android name="android.intent.category.LAUNCHER" / /intent-filter /activity 他にも幾つかのIntent Filterアクションおよびカテゴリーがあるが、アプリアイコンから起動する場合はこの指定が必要だと覚えておけばよい。 他のアプリから 特定の Intentアクションにより起動されるアプリは、別の指定を追加する必要がある。 Intent(インテント:意図) 特定のアクティビティを指定、または「何をしたいのか」を指定し別のアプリを起動する。 同アプリ内のアクティビティ間連携にも使用される。 例:明示的に特定のアクティビティを指定し、EditTextボックスの入力値を渡している Intent intent = new Intent(this, DisplayActivity.class); EditText editText = (EditText) findViewById(R.id.input_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); 例:データ表示を指定し、Webページを開く Uri uri = Uri.parse("http //www.android.com"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); 簡略化のため省いているが、通常は事前に実行可能なIntentかチェックするためPackageManagerを使用する。この Intentで開かれるアプリは Intent Filterにて ACTION_VIEWアクションを受け付ける指定があるものの中から選ばれる。 リソース アプリが利用する画像ファイル、レイアウト定義、言語ごとの文字列ファイルなどをひとまとめにし、Rクラスを通じた共通のアクセス方法を提供する。画像、動画、音声などのデータファイル、XMLファイルで構成される。 リソースは異なる解像度、画面サイズ、言語に対応するディレクトリに分けて構成することで自動的に対応するディレクトリ内のファイルが利用されるように最適化される。詳細はこちら その他 基本の4コンポーネント種とリソースの他に、これらをサポートするコンポーネントが幾つかある。 Intent Fragment
https://w.atwiki.jp/api_programming/pages/195.html
下位ページ インテントとインテントフィルタ サービス(Service) ストレージオプション フラグメント(Fragment) プロセスとスレッド(processes and threads) リストビュー(List View) レイアウト(Layout) 入力コントロール(Controls) 設定(Setting) 通知(Notification) Content スピナーコントロールの設定レイアウトの準備 選択肢の設定string.xmlでの設定 プログラム側から値を選択する アクティビティアプリの閉じられ方で、挙動が異なる アクションバーの代わりに、ツールバーを使うアクションバーを消す ツールバーをレイアウトに追加する Activity内で、アクションバーの代わりに使う記述をする スライドメニューを実装するドロワーレイアウトを作成する ドロワービューの中身を準備するListViewで作る 別のXMLファイルで作る ドロワーのオープン・クローズを実装する バックグラウンド処理(サービス) 閉じられても動作するサービスを動かすServiceクラスの作成 Activityから、作成したサービスを動かす 加速度センサの情報を受ける 回転角の情報を受け取る回転角の解釈 画面の回転を抑制するAndroidManifest.xmlで抑制する 動的に(プラグラム内で)で抑制する インテントにオブジェクトの情報を乗っけるparcelable をインプリメントしたクラスをつくるParcelable.Creater フィールドの実装 BundleやIntentに情報を乗せる Activity側で受ける 複数の情報をリストにして表示する バイブレーションを一定時間、作動させるパーミッションの追加 Vibratorオブジェクトを生成する vibrateを実行する 通知バーにバックグラウンド起動中の表示を出す 裏返したときの方向で、記録を分ける メニューのバーを設定するメニューリソースを準備するフォルダの作成 リソースファイルの作成 設定したメニューファイルを、Activityのメニューバーに評させる メニューの選択を受け取る処理を作る チェックボックスを動作させる 設定画面を設定する/設定情報をローカルストレージに残す 記録内容をGoogleスプレッドシートに記録する 記録内容をGoogleカレンダーに記録するブラウザでURLを開く ブラウザを開くURIとして、認証ページを指定する リダイレクトを受け取る 受け取ったリダイレクトをデータに紐解く codeを送って、tokenを受け取る tokenを保存する 終了時間と開始時間から、時間の計算をする リストビューで独自レイアウトを設定する USBデバッグ リリースビルド スピナーコントロールの設定 [部分編集] レイアウトの準備 Spinner android id="@+id/planets_spinner" android layout_width="fill_parent" android layout_height="wrap_content" / 選択肢の設定 string.xmlでの設定 まずは、string.xmlに文字配列を作る string-array name="planets_array" item Mercury /item item Venus /item item Earth /item /string-array この文字配列をアダプタにして、スピナーコントロールにアダプタをするリソースのアダプタ化には、ArrayApapter.createFromResource を使用できる。simple_spinner_item はデフォルト外観を設定している。通常はこれで良し。 setDropDownViewResource(int) は選択時に一覧を表示するのに使う。なくても一応ドロップダウンは出てくるが、ちょっとしょぼい? Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter CharSequence adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); createFromResource - ArrayAdapter | Android Developers setDropDownViewResource - ArrayAdapter | Android Developers プログラム側から値を選択する Spinner.setSelection で位置を指定する。その位置を取得するにはAdapterを使う。 使っているアダプタを取得するobjSpinner.getAdapter でアダプタを取得できる objAdapter.getPosition("...") でセレクタの位置を取得値が見つからなかったら -1 が返る objSpinner.setSelection に先程取得した位置を設定する ArrayAdapter spinnerAdapter = (ArrayAdapter) objSpinner.getAdapter(); int i = spinnerAdapter.getPosition("value"); objSpinner.setSelection(i); getAdapter - AbsSpinner | Android Developers getPosition - ArrayAdapter | Android Developers setSelection - AbsSpinner | Android Developers アクティビティ アプリの閉じられ方で、挙動が異なる onDestroyが呼ばれない限りは、Serviceを使わずとも、 ↓にある通り、ホームボタンとバックボタンでアプリケーションから離れた場合で挙動が違う。 https //kokufu.blogspot.jp/2011/03/activity.html 説明として、 ホームボタン:ホームアプリケーションが起動している バックボタン:Activityスタックからポップしている と書いてあったが、気持ち悪いのは、□ボタンを押すとあたかもまだ生きているかのように、アプリケーションリストに表示されるから。画面上に残っているが実際には onDestroy で消えている。 このあたりが、「アプリケーションをスワイプして消しても消さなくてもメモリにはそれほど影響しない」ということなんだろうか。 アクションバーの代わりに、ツールバーを使う [部分編集] 今後の拡張性から、アクションバーよりツールバーを使ったほうが良い、という記述をちょこちょこ見かけるが、Android Studioでプロジェクトを作ると、基本はアクションバーが設定されている。これをツールバーに置き換える。 アプリバーの追加 | Android Developers Toolbar | Android Developers AndroidのToolBar(新しいActionBar)メモ | Qiita アクションバーを消す res/values/styles.xmlで AppThemeのテーマを変更する style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" ツールバーをレイアウトに追加する android.support.v7.widget.Toolbar android id="@+id/toolbar" android layout_width="match_parent" android layout_height="wrap_content" / レイアウトの@android */* ,?attr/* ,?* ,?android attr/* の違い | Qiita Activity内で、アクションバーの代わりに使う記述をする /* ToolBarの設定 */ Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); toolbar.setTitleTextColor(Color.WHITE); // 設定をしておく setSupportActionBar(toolbar); // アクションバーの代わり、という設定 これを書かないと、画面上では何も表示されない(空間だけはある) スライドメニューを実装する [部分編集] NavigationDrawer が正式名称? DrawerLayout | Android Developers ナビゲーションドロワーの作成 | Android Developers ドロワーレイアウトを作成する レイアウトxmlにて、DrawerLayout オブジェクトをレイアウトのルートビューとして指定する。 ルートの中にドロワービューとメインビューを設定する順序はメインビューを先にする高さはルートに合わせる(match_parent) 次にドロワーのビューを指定するlayout_gravityを指定する(layout_gravity:どっちにくっつけるか、どちら方向から出てくるか?)右から左に出す場合にはstart layout_heightは親ビューと同じ高さを指定する layout_widthはすべての情報が見える幅を指定する ドロワービューの中身を準備する ListViewで作る ListViewの中に android layout_gravity="..." を入れないと、スライドで入ってくる設定にならず、重ねて見えている状態になる android background="#111" 背景がないと、中途半端にすけた状態で表示される。 別のXMLファイルで作る NavigationViewで作った場合、ヘッダ部分とメニュー部分をそれぞれレイアウトとメニューで作成する app headerLayout="@layout/drawer_header" app menu="@menu/drawer" ドロワーのオープン・クローズを実装する DrawerLayout にリスナーをセットする。このリスナーは DrawerLayout.DrawerListener を実装して、使う。 Activity にアクションバーがセットされている場合は ActionBarDrawerToggle が DrawerLayout.DrawerListener を実装する。 DrawerLayout mDrawerLayout = ...; ActionBarDrawerToggle mDrawerToggle; mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) {...} public void onDrawerOpened(View drawerView) {...} }; // Set the drawer toggle as the DrawerListener mDrawerLayout.setDrawerListener(mDrawerToggle); 【Android】スライドして表示されるメニュー | Qiita Navigation Drawer の概要 | Android 開発入門 Navigation Drawer の基本的な実装方法 | Android 開発入門 バックグラウンド処理(サービス) サービス - Android Developers Androidアプリでのバックグラウンド処理と通知機能 | Android Studio 2で始めるアプリ開発入門 - CodeZine 流れ Serviceのサブクラスを作成する AndroidManifest.xmlにサービスを登録 サブクラスで、必要なクラスをオーバーライドする。次のあたり。onCreate() onStartCommand() onDestroy() アクティビティからサービスを起動する (きちっと止まるように設計しておく) 閉じられても動作するサービスを動かす バックグラウンドで動作させるためにはServiceを用いる。 Serviceクラスの作成 Activityのように、作成・開始などのイベントで動くが、おもに3つ。 onCreate onStartCommand onDestroy Service | Android Developers Activityから、作成したサービスを動かす startServiceで起動、stopService(stopSelf)で停止。忘れずにServiceを止めないと、いつまでも動き続ける。 startService、stopServiceなどには、インテントを準備して、サービスにそれをなげる形をとっている。 startService - Context | Android Developers stopService - Context | Android Developers stopSelf - Service | Android Developers 加速度センサの情報を受ける 回転角の情報を受け取る センサーは加速度まではそのまま読み取れるが、回転角は加速度情報、地磁気情報から計算する必要がある。まず getRotationMatrix で回転行列を求め、getOrientation で回転行列を回転角に変換する(計算する) getRotationMatric - SensorManager | Android Developers getOrientation - SensorManager | Android Developers 引数に取った2つの配列には、傾斜行列、回転行列(の情報)が計算されて入ってくる。情報が不要ならnullでよい。 回転角の解釈 正位置として Zは天を指す Yは磁北を指す Xは Y,Z の外積を指す 画面の回転を抑制する AndroidManifest.xmlで抑制する 回転させないActivityに android screenOrientation="portrait" を追加すると、縦向き固定になる activity | Android Developers 動的に(プラグラム内で)で抑制する Activity内で、setRequestedOrientation を呼び出す setRequestedOrientation - Activity | Android Developers screenOrientation - ActivityInfo | Android Developers インテントにオブジェクトの情報を乗っける bundleで多くの情報をわたすような方法として、putParcelableArrayList くらいしか見当たらないので、これを使う。そのためには、Parcelable をimplements したようなクラスを作る必要がある。 Bundle | Android Developers parcelable をインプリメントしたクラスをつくる Parcelable実装にはParcelable.Createorというstatic fieldが必要。そのフィールドの初期化にて、Parcelに保存したデータを復元するためのコンストラクタを呼ぶ。 Parcelable | Android Developers Parcelable.Creater フィールドの実装 Parcelable.Creater | Android Developers createFromParcel(Parcel source)Parcelable.writeToParcel() で書き出されたParcelデータをインスタンス化する → コンストラクタを作っておく newArray(int size)ParcelableクラスのArrayを作る BundleやIntentに情報を乗せる IntentならputParcelableArrayListExtra、BundleならputParcelableArrayList で情報を登録 putParcelableArrayListExtra - Intent | Android Developers getParcelableArrayList - Bundle | Android Developers Activity側で受ける IntentならgetParcelableで受けられる。受けたときにすでにParcelableをimplementしたオブジェクトで受けられる。 getParcelableArrayListExtra - Intent | Android Developers getParcelableArrayList - Bundle | Android Developers 複数の情報をリストにして表示する [https //www54.atwiki.jp/api_programming/pages/202.html] バイブレーションを一定時間、作動させる Vibratorインスタンスからvibrate()を実行する。バイブレーションの実施にはAndroidManifest.xmlにパーミッションの追加が必要。 パーミッションの追加 マニフェストにパーミッションを追加する - パーミッションの宣言 | Android Developers Vibratorオブジェクトを生成する getSystemServiceでVibratorオブジェクトを生成する Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); getSystemService - Context | Android Developers Vibrator | Android Developers vibrateを実行する 幾つかパターンはあるが、かんたんなところで、これ。 vibrator.vibrate(500); vibrate - Vibrator | Android Developers 通知バーにバックグラウンド起動中の表示を出す 裏返したときの方向で、記録を分ける メニューのバーを設定する メニューリソースを準備し、表示させる。そのうえで、メニューのタップ動作に対する反応を記述する メニュー | Android Developers メニューリソースを準備する フォルダの作成 デフォルトではメニュー用のフォルダが無い(かもしれない)ので、res/menuを追加し、ここに入れておく。 resフォルダ右クリック [New]>[Android resource directory]を選択 ダイアログで、「Resource type 」から「menu」を選択し、OK リソースファイルの作成 menuフォルダを右クリック [New]>[Menu resource file] ファイル名を入力し、OK ファイル内に menu item / item / /menu を記述(実際はidやタイトルを設定する必要あり) Menu Resource | Android Developers 設定したメニューファイルを、Activityのメニューバーに評させる onCreateOptionMenuをオーバーライドして、この中でリソースの指定などを行う。XMLのメニューを実際?のメニューオブジェクトに変換するのに、inflatorを使用できる。 @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); //(1) inflater.inflate(R.menu.menu_options_menu_list, menu); //(2) return super.onCreateOptionsMenu(menu); //(3) } onCreateOptionMenu - Activity | Android Developers メニューの選択を受け取る処理を作る オプションメニューを作っていれば、その受取はonOptionsItemSelectedをオーバーライドして処理できる。 @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } このとき、itemにクリックされた情報が入っているので、これを紐解いて、どのメニューがクリックされたか判断し、switchなどで処理する。 int itemId = item.getItemId(); Android 3.0(APIレベル11)以降では メニューリソースXMLのitemに、android onClick を記述しておくことで、動作を定義させることもできる。 チェックボックスを動作させる Android/入力コントロール(Controls) 設定画面を設定する/設定情報をローカルストレージに残す Android/設定 記録内容をGoogleスプレッドシートに記録する http //qiita.com/konnobu/items/8bec3d5a45235fc88a08 記録内容をGoogleカレンダーに記録する 多分、クライアント用のライブラリが作られていて、簡単に認証処理をしたり、データを取得したりできるようになっていると思われるが、別サイトでも転用が聞くように、地道な方法を取ってみる。というか、専用のライブラリの使い方をよくわかっていない。 流れは OAuth2.0で認証Google API にプロジェクトと登録(キーの発行) 認証コードを発行 受け取り コードを access token と交換 access token も使って、リクエスト送信 こまごまと引っかかった場所が多数。 AndroidManifest.xmlにパーミッションの設定が必要 ブラウザでURLを開く Android/インテントとインテントフィルタ ブラウザを開くURIとして、認証ページを指定する GoogleのOAuth2認証 OAuth2認証 | Android Developers Step 1 Send a request to Google's OAuth 2.0 server | Google Identify Platform リダイレクトを受け取る 大概の(google 以外でも)場合は、認証後に指定したリダイレクト先に飛ばしてくれる。そのスキーム名に応じて、Android側でどのアプリで開くのかを考えてくれる。Android に「このスキームがきたら、俺のアプリで開いて」と指示するためには、AndroidManifest.xml に記述する必要がある。 scheme // host port / path intent-filter内で、action, category, data を指定する。上記のリダイレクト先に対応する内容を書くのは data で、scheme は data android scheme="com.example.testproject" / のようになる。 Intent の 定数として ACTION_VIEW などが定義されているが、実体は文字列で、それが android.intent.action.VIEW などになる(ので、どれを設定するかはIntent を参照)。ブラウザでどんなスキームがきたらヨソになげるのか、どんな action として投げるのか、説明されている場所がわからないが、ひとまず action ACTION_VIEW category CATEGORY_BROWSABLR scheme ここは各自で で開けた。redirect_uri で scheme //~ が指定できない( /だけ)なので、hostは存在せず、pathだけ。 インテント解決 - インテントとインテント フィルタ | Android Developers Intent - Android Developers 受け取ったリダイレクトをデータに紐解く 一旦受け取れれば、中身は getIntent() を経由して、中身を見られる(Intent.getAction(), Intent.getCategories() など)。OAuth では、path のなかに code を入れて返してくるので、Dataのなかを探せばある Intent intent = getIntent(); String data = intent.getDataString(); とすると、googleの認証で指定した redirect_uri のあとに code がくっついて返ってきている。以下、サンプル com.example.####.#### /oauth2callback?code=4/8abcdefg# 上記の場合、oauth2callback を uri.getPath() で、4/8abcdefg# を getQueryParameter("code") で受け取れる。 getIntent - Activity | Android Developers getData - Intent | Android Developers getQueryParameter - Uri | Android Developers codeを送って、tokenを受け取る コードと必要情報を POST することで、access token との交換をする。この処理は、UIスレッドだとエラーになるので、AsyncTaskで実行する必要がある。 また、交換がうまく行かなかったときは、HttpURLConnection の getInputStream ではなく、 getErrorStream に情報が流れるため、プログラムの確認作業では注意。(この辺をよくわかっていなくて、エラー原因を探すのに苦労した。) redirect_uri はスキームもパスもコード発行依頼時と同じものを使う。 Android/プロセスとスレッド(processes and threads) Async Task | Android Developers tokenを保存する プレファレンスへの保存 終了時間と開始時間から、時間の計算をする リストビューで独自レイアウトを設定する https //www54.atwiki.jp/api_programming/editx/202.html USBデバッグ http //www.aiseesoft.jp/tutorials/android-debug-mode.html リリースビルド http //androidstudio.hatenablog.com/entry/2014/07/26/154043
https://w.atwiki.jp/taskeru/pages/34.html
Taskerから直接実行すると便利なActivity misc component activity で利用可能 アプリ名 動作 指定Activity ジョルテ 新規作成 jp.co.johospace.jorte.gcal.EditEvent ビジネスカレンダー 新規作成 net.geniusbizcal.NewEditEventActivity SwipeSwitcher 前のアプリに戻る(除外リストあり) com.appspot.eikatou0.ss.TaskSwitchActivity PowerAMP ライブラリ表示(通常設定はplayerにして、これもswipepadに登録すると捗る?) com.maxmpz.audioplayer.PlayListChooser OS標準 無くしたときのためのデータリセット com.android.settings.SecFactoryReset 2chMate 巡回Sync2ch同期p2同期 jp.syoboi.a2chMate.action.reloadBookmarkjp.syoboi.a2chMate.action.sync2chjp.syoboi.a2chMate.action.p2sync Intent リスト一覧を表示するアプリ GetIntentList Activity Getter マケにある intent intercept は、実際に intent が発動する毎にそれがどんな挙動をしているか、他に同じ intent を受信出来るアプリはどれなのかを表示してくれる こちらは、アプリ上でコピーも出来る Intent Intercept QuickShortcutMaker で実際に動かせるが… data や extra は渡せない
https://w.atwiki.jp/android/pages/28.html
概要 Activity は androidに表示される画面の単位。 ただしダイアログなどは含まない。ヒストリの扱いが違う。 ベースクラスのContext に色々と便利な機能が用意されている。 ライフサイクル 作成、可視、対話中 という3つの状態を遷移する。あとヒストリの関係でonFreezeとonRestartが存在する。 onCreate Activityが作成された。 UIの初期化 Bundleからデータを読む onStart Activityの表示が開始される。 初回はonResumeに続く。 もしonStop()の後に再開した場合はonRestart()に続く。 onRestart Activityの表示の再開。 初回 onCreate()→onStart() →onResume() それ以外 onStop()→onStart()→onRestart()→onResume() onResume Activityはユーザとの対話を開始する。 onFreeze Activityはユーザとの対話を中断する。 データの永続化を行うこと。 Bundleにデータを保存 常にonPauseに続く。 onPauseとの主な違いはヒストリスタック上の扱い。android.content.IntentReceiverを参照。 onPause Activityはユーザとの対話を中断する。 アニメーション表示の停止などを行うこと。 対話が再開する場合はonResumeに続く。 非表示状態が続いた場合はonStopに続く。 onStop Activityは表示を中断する。 ActivityはonStartとonRestartの呼び出しの後に再開するか、 onDestroyの呼び出しの後に破棄される。 また、他のアプリケーションがメモリを要求した場合はプロセスごとkillされる。 onDestroy Activityが破棄される。 finish()からも呼ばれるため、区別のために isFinishing() メソッドが用意されている。
https://w.atwiki.jp/android-reference/pages/22.html
android.app High-level classes encapsulating the overall Android application model. Interfaces DatePickerDialog.OnDateSetListener The callback used to indicate the user is done filling in the date. KeyguardManager.OnKeyguardExitResult Callback passed to exitKeyguardSecurely(KeyguardManager.OnKeyguardExitResult) to notify caller of result. PendingIntent.OnFinished Callback interface for discovering when a send operation has completed. SearchManager.OnCancelListener See setOnCancelListener(SearchManager.OnCancelListener) for configuring your activity to monitor search UI state. SearchManager.OnDismissListener See setOnDismissListener(SearchManager.OnDismissListener) for configuring your activity to monitor search UI state. TimePickerDialog.OnTimeSetListener The callback interface used to indicate the user is done filling in the time (they clicked on the Set button). Classes Activity An activity is a single, focused thing that the user can do. ActivityGroup A screen that contains and runs multiple embedded activities. ActivityManager Interact with the overall activities running in the system. ActivityManager.MemoryInfo Information you can retrieve about the available memory through getMemoryInfo(ActivityManager.MemoryInfo). ActivityManager.ProcessErrorStateInfo Information you can retrieve about any processes that are in an error condition. ActivityManager.RecentTaskInfo Information you can retrieve about tasks that the user has most recently started or visited. ActivityManager.RunningAppProcessInfo Information you can retrieve about a running process. ActivityManager.RunningServiceInfo Information you can retrieve about a particular Service that is currently running in the system. ActivityManager.RunningTaskInfo Information you can retrieve about a particular task that is currently "running" in the system. AlarmManager This class provides access to the system alarm services. AlertDialog A subclass of Dialog that can display one, two or three buttons. AlertDialog.Builder AliasActivity Stub activity that launches another activity (and then finishes itself) based on information in its component s manifest meta-data. Application Base class for those who need to maintain global application state. DatePickerDialog A simple dialog containing an DatePicker. Dialog Base class for Dialogs. ExpandableListActivity An activity that displays an expandable list of items by binding to a data source implementing the ExpandableListAdapter, and exposes event handlers when the user selects an item. Instrumentation Base class for implementing application instrumentation code. Instrumentation.ActivityMonitor Information about a particular kind of Intent that is being monitored. Instrumentation.ActivityResult Description of a Activity execution result to return to the original activity. IntentService An abstract Service that serializes the handling of the Intents passed upon service start and handles them on a handler thread. KeyguardManager Class that can be used to lock and unlock the keyboard. KeyguardManager.KeyguardLock Handle returned by newKeyguardLock(String) that allows you to disable / reenable the keyguard. LauncherActivity Displays a list of all activities which can be performed for a given intent. LauncherActivity.IconResizer Utility class to resize icons to match default icon size. LauncherActivity.ListItem An item in the list ListActivity An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. LocalActivityManager Helper class for managing multiple running embedded activities in the same process. Notification A class that represents how a persistent notification is to be presented to the user using the NotificationManager. NotificationManager Class to notify the user of events that happen. This is how you tell the user that something has happened in the background. PendingIntent A description of an Intent and target action to perform with it. ProgressDialog A dialog showing a progress indicator and an optional text message or view. SearchManager This class provides access to the system search services. Service A Service is an application component that runs in the background, not interacting with the user, for an indefinite period of time. TabActivity An activity that contains and runs multiple embedded activities or views. TimePickerDialog A dialog that prompts the user for the time of day using a TimePicker. Exceptions PendingIntent.CanceledException Exception thrown when trying to send through a PendingIntent that has been canceled or is otherwise no longer able to execute the request. コメント 名前 コメント すべてのコメントを見る