Санкт-Петербургский государственный университет
Опубликован: 24.10.2012 | Доступ: свободный | Студентов: 8637 / 1151 | Оценка: 4.00 / 4.00 | Длительность: 05:26:00
Специальности: Системный архитектор
Самостоятельная работа 1:

Практика разработки простейших приложений для Android

< Лекция 1 || Самостоятельная работа 1: 12 || Лекция 2 >

2.4.5. Работа с GPS

На экране представлена следующая информация о местоположении (Рис 2.4):

Запущенное на эмуляторе приложение Location Example

Рис. 2.4. Запущенное на эмуляторе приложение Location Example
  • Статус (уведомление о том, когда были получены данные)
  • Широта
  • Долгота
  • Импортируйте в рабочую область проект Location Example.
  • Запустите его на эмуляторе. На экране появится уведомление "Waiting for location".
  • Теперь виртуальному устройству необходимо передать информацию о местоположении. Для этого, не закрывая окно эмулятора, запустите DDMS (Window -> Open Perspective -> Other -> DDMS) и через вкладку Emulator Control отправьте устройству необходимые данные (Рис 2.5).
    Значения долготы и широты отправляются на эмулятор с помощью DDMS

    Рис. 2.5. Значения долготы и широты отправляются на эмулятор с помощью DDMS
  • Убедитесь, что программа работает корректно, и эмулятор вывел полученную информацию о местоположении.
  • Обратите внимание на тег <uses-permission> в файле AndroidManifest.xml и подумайте, зачем он прописывается в данном приложении.
  • Откройте файл src/MainActivity.java и постарайтесь разобраться, как происходит жизненный цикл Activity данного приложения, и какие действия совершаются на каждом этапе.

Приложение к лабораторной работе

Данное приложение содержит тексты программ, рассматриваемых в примерах.

  1. Button Example
    • res/layout/activity_main.xml
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.application"
          android:versionCode="1"
          android:versionName="1.0" >
      
          <uses-sdk
              android:minSdkVersion="8"
              android:targetSdkVersion="15" />
      
          <application
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name">
              <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>
          </application>
      
      </manifest>
    • src/MainActivity.java 
      
      package com.example.application;
      
      import android.app.Activity;
      import android.graphics.Color;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      import android.widget.LinearLayout;
      import android.widget.Toast;
      
      public class MainActivity extends Activity implements OnClickListener {
      
        private Button switchToGreen;
        private Button switchToRed;
        private Button switchToBlue;
        private LinearLayout screenLayout;
        private Toast informationToast;
      
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          // init buttons
          switchToBlue = (Button) findViewById(R.id.switchBlue);
          switchToGreen = (Button) findViewById(R.id.switchGreen);
          switchToRed = (Button) findViewById(R.id.switchRed);
          screenLayout = (LinearLayout) findViewById(R.id.screenLayout);
      
          // setup listeners
          switchToBlue.setOnClickListener(this);
          switchToRed.setOnClickListener(this);
          switchToGreen.setOnClickListener(this);
      
          informationToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        }
      
        public void onClick(View view) {
          if (switchToBlue.equals(view)) {
            screenLayout.setBackgroundColor(Color.BLUE);
            showToast("Hello blue");
          } else if (switchToRed.equals(view)) {
            screenLayout.setBackgroundColor(Color.RED);
            showToast("Hello red");
          } else if (switchToGreen.equals(view)) {
            screenLayout.setBackgroundColor(Color.GREEN);
            showToast("Hello green");
          }
      
        }
      
        private void showToast(String text) {
          informationToast.cancel();
          informationToast.setText(text);
          informationToast.show();
        }
      }
  2. Animation Example
    • res/anim/frame_anim.xml
      <?xml version="1.0" encoding="utf-8"?>
      <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
          android:oneshot="false" >
      
          <item
              android:drawable="@drawable/ic_launcher"
              android:duration="200"/>
          <item
              android:drawable="@drawable/ic_launcher1"
              android:duration="200"/>
          <item
              android:drawable="@drawable/ic_launcher2"
              android:duration="200"/>
          <item
              android:drawable="@drawable/ic_launcher3"
              android:duration="200"/>
      
      </animation-list>
    • res/anim/transform_anim.xml
      <?xml version="1.0" encoding="utf-8"?>
      <set xmlns:android="http://schemas.android.com/apk/res/android"
          android:shareInterpolator="false" >
      
          <scale
              android:duration="700"
              android:fillAfter="false"
              android:fromXScale="1.0"
              android:fromYScale="1.0"
              android:interpolator="@android:anim/accelerate_decelerate_interpolator"
              android:pivotX="50%"
              android:pivotY="50%"
              android:toXScale="1.4"
              android:toYScale="0.6" />
      
          <set android:interpolator="@android:anim/decelerate_interpolator" >
              <scale
                  android:duration="400"
                  android:fillBefore="false"
                  android:fromXScale="1.4"
                  android:fromYScale="0.6"
                  android:pivotX="50%"
                  android:pivotY="50%"
                  android:startOffset="700"
                  android:toXScale="0.0"
                  android:toYScale="0.0" />
      
              <rotate
                  android:duration="400"
                  android:fromDegrees="0"
                  android:pivotX="50%"
                  android:pivotY="50%"
                  android:startOffset="700"
                  android:toDegrees="-45"
                  android:toYScale="0.0" />
          </set>
      
      </set>
    • src/MainActivity.java
      
      package com.example.application;
      
      import android.app.Activity;
      import android.graphics.Color;
      import android.graphics.drawable.AnimationDrawable;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.view.animation.Animation;
      import android.view.animation.AnimationUtils;
      import android.widget.Button;
      import android.widget.ImageView;
      
      public class MainActivity extends Activity implements OnClickListener {
        
        private Button startFrameAnim;
        private Button startTransformAnim;
        private Button cancelAnim;
        private ImageView animationView;
      
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          
          startFrameAnim = (Button) findViewById(R.id.frameAnimationStart);
          startTransformAnim= (Button) findViewById(R.id.transformAnimationStart);
          cancelAnim = (Button) findViewById(R.id.cancelAnimation);
          animationView = (ImageView) findViewById(R.id.animationView);
          
          startFrameAnim.setOnClickListener(this);
          startTransformAnim.setOnClickListener(this);
          cancelAnim.setOnClickListener(this);
        }
      
        public void onClick(View v) {
          if (startFrameAnim.equals(v)) {
            animationView.setBackgroundResource(R.anim.frame_anim);
        AnimationDrawable animation = 
      (AnimationDrawable) animationView.getBackground();
            animation.start();
          } else if (startTransformAnim.equals(v)) {
            animationView.setBackgroundResource(R.drawable.ic_launcher);
        Animation transformAnimation = 
      AnimationUtils.loadAnimation(this, R.anim.transform_anim);
            animationView.startAnimation(transformAnimation);
          } else if (cancelAnim.equals(v)) {
            animationView.setBackgroundColor(Color.BLACK);
          }
        }
      }
  3. Location Example
    • src/MainActivity.java
      
      package com.example.application;
      
      import java.util.Date;
      
      import android.app.Activity;
      import android.location.Criteria;
      import android.location.Location;
      import android.location.LocationListener;
      import android.location.LocationManager;
      import android.os.Bundle;
      import android.widget.TextView;
      
      public class MainActivity extends Activity implements LocationListener {
        private TextView latitudeLabel;
        private TextView longitudeLabel;
        private TextView statusLabel;
        private LocationManager locationManager;
      
        @Override
        public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          latitudeLabel = (TextView) findViewById(R.id.latitudeLabel);
          longitudeLabel = (TextView) findViewById(R.id.longitudeLabel);
          statusLabel = (TextView) findViewById(R.id.statusLabel);
      
      locationManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        }
      
        @Override
        protected void onResume() {
          super.onResume();
          // construct a criteria with best accuracy
          Criteria criteria = new Criteria();
          criteria.setAccuracy(Criteria.ACCURACY_FINE);
          // get best ENABLED provider that meets the criteria
          String provider = locationManager.getBestProvider(criteria, true);
          // request the updates
          locationManager.requestLocationUpdates(provider, 0, 0, this);
        }
      
        @Override
        protected void onPause() {
          super.onPause();
          locationManager.removeUpdates(this);
        }
      
        public void onLocationChanged(Location location) {
          statusLabel.setText("Location recieved at " + new Date());
          latitudeLabel.setText("Latitude: " + location.getLatitude());
          longitudeLabel.setText("Longitude: " + location.getLongitude());
        }
      
        public void onProviderDisabled(String provider) {
        }
      
        public void onProviderEnabled(String provider) {
        }
      
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
      }
    • AndroidManifest.xml
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.application"
          android:versionCode="1"
          android:versionName="1.0" >
      
          <uses-sdk
              android:minSdkVersion="8"
              android:targetSdkVersion="15" />
          
          <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
          <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      
          <application
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name">
              <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>
          </application>
      
      </manifest>
< Лекция 1 || Самостоятельная работа 1: 12 || Лекция 2 >
Несипбай Сагыныш
Несипбай Сагыныш
Сергей Петров
Сергей Петров