zoukankan      html  css  js  c++  java
  • [转]大话企业级Android应用开发实战 Activity

                          16 “机器人”的管理员——Activity 

    2.编写EventActivity.java

    public class EventActivity extends Activity {

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

        }

        @Override

        public boolean onKeyDown(int keyCode, KeyEvent event) {    

            showInfo("按键,按下");

            return super.onKeyDown(keyCode, event);

        }

        @Override

        public boolean onKeyUp(int keyCode, KeyEvent event) {

            showInfo("按键,弹起");

            return super.onKeyUp(keyCode, event);

        }

        @Override

        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();

            float y = event.getY();

            showInfo("你单击的坐标为:("+x+":"+y+")");

            return super.onTouchEvent(event);

        }  

        public void showInfo(String info){

            Toast.makeText(EventActivity.this, info, Toast.LENGTH_LONG).show();

        }

    }

     

    16.1  Activity生命周期

    2.编写MainActivity.java

    首先要重写七个相应被触发的方法,以日志的形式输出相应的事件信息。然后添加两个button,一个用来启动新的Activity,另一个是用来退出当前Activity。

    public class MainActivity extends Activity {

        private static final String TAG = "MainActivity";

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Log.i(TAG, "onCreate()"); 

            Button button =(Button) this.findViewById(R.id.button);

            Button button1 =(Button) this.findViewById(R.id.button1);

    button.setOnClickListener(new View.OnClickListener() {     

                public void onClick(View v) {

                        Intent intent = new Intent(MainActivity.this, Other

    Activity.class);

                        startActivity(intent);

                    }

                }

            });

            button1.setOnClickListener(new View.OnClickListener() {     

                @Override

                public void onClick(View v) {

                    finish();

                }

            });

        }

        @Override

        protected void onDestroy() {

            Log.i(TAG, "onDestroy()");

            super.onDestroy();

        }

        @Override

        protected void onPause() {

            Log.i(TAG, "onPause()");

            super.onPause();

        }

        @Override

        protected void onRestart() {

            Log.i(TAG, "onRestart()");

            super.onRestart();

        }

        @Override

        protected void onResume() {

            Log.i(TAG, "onResume()");

            super.onResume();

        }

        @Override

        protected void onStart() {

            Log.i(TAG, "onStart()");

            super.onStart();

        }

        @Override

        protected void onStop() {

            Log.i(TAG, "onStop()");

            super.onStop();

        }

    }

    16.2  为应用添加新的Activity

    16.2.1  利用Activity实现页面转换

    2.编写main.xml

    在main.xml中加入一个按钮,代码如下:

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        >

    <TextView 

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="这是第一页"

        />

       <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="下一页"

       ></Button>

    </LinearLayout>

    3.编写two.xml

    然后新建一个Layout文件,two.xml,代码如下:

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        >

    <TextView 

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="这是第二页"

        />

       <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="上一页"

       ></Button>

    </LinearLayout>

     

    4.编写OneActivity.java

    代码如下:

    public class OneActivity extends Activity {

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {

                     nextLayout();//显示下一个页面

                }

            });

     

        }

        public void nextLayout(){

        setContentView(R.layout.two);

          Button upButton=(Button)findViewById(R.id.up);

          upButton.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {   //显示上一个页面

                    upLayout();

                }

     

            });

        }

        public void upLayout() {

        setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {

                     nextLayout();//显示下一个页面

                }

            });

           

        }

    }

     

    16.2.2  添加Activity

    在other.xml中加入一个TextView,代码如下:

    other.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout

      xmlns:android="http://schemas.android.com/apk/res/android"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent">

      <TextView

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:text="第二个Activity"

      ></TextView>

    </LinearLayout>

     

    在main.xml中加入一个button,代码如下:

    main.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        >

    <TextView  

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="第一个Activity"

        />

       <Button

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:id="@+id/next"

         android:text="打开新的Activity"

       ></Button>

    </LinearLayout>

     

    2.编写MainActivity.java

    代码如下:

    MainActivity.java

    public class MainActivity extends Activity {

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    //打开other activity

                    //Intent用于激活组件(Activity)和在组件之间传递数据

                    Intent intent = new Intent(MainActivity.this,

    OtherActivity.class);//激活OtherActivity

     

                }

            });

        }

    }

    然后在OtherActivity中实现onCreate()方法,加载other.xml,代码如下:

    public class OtherActivity extends Activity {

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.other);

            }

    }

    在AndroidManifest.xml文件中注册OtherActivity,代码如下:

    AndroidManifest.xml

     

    <?xml version="1.0" encoding="utf-8"?>

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"

          package="com.sharpandroid.many"

          android:versionCode="1"

          android:versionName="1.0">

        <application android:icon="@drawable/icon" android:label="@string/

    app_name">

            <activity android:name=".MainActivity"

                      android:label="@string/app_name">

                <intent-filter>

                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />

                </intent-filter>

            </activity>

          <activity android:name=".OtherActivity"

                     android:label="@string/app_name">

                      </activity>

        </application>

        <uses-sdk android:minSdkVersion="7" />

    </manifest>

    16.2.3  得到新打开的Activity关闭后返回的数据

    首先,在other.xml中加入一个关闭按钮,代码如下:

    Other.xml

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout

      xmlns:android="http://schemas.android.com/apk/res/android"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent">

      <TextView

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:id="@+id/other"

         android:text="第二个Activity"

      ></TextView>

      <Button

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:id="@+id/close"

         android:text="关闭"

      ></Button>

    </LinearLayout>

    在OtherActivity关闭之前,把要返回的数据放入到Intent中,然后调用OtherActivity的setResult()方法,代码如下:

    public class OtherActivity extends Activity {

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.other);

            Intent intent = this.getIntent();//得到激活该组件的意图

           

            Bundle bundle= intent.getExtras();

          

           String name=bundle.getString("name");

           int age=bundle.getInt("age");

            TextView paramView = (TextView) this.findViewById(R.id.other);

            paramView.setText("名称:"+ name + "  年龄:"+ age); //显示数据

           

            Button button=(Button)findViewById(R.id.close);

            Button.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {

                    Intent data=new Intent();

                    data.putExtra("name", "王三");

                    data.putExtra("age", 23);  //要返回的数据

                    OtherActivity.this.setResult(1, data);//设置返回码和数据,

    返回码可以任意

                    OtherActivity.this.finish();//关闭Activity

                   

                }

            });

            }

    }

    编写MainActivity.java:

    public class MainActivity extends Activity {

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {

                    Intent intent = new Intent(MainActivity.this,

    OtherActivity.class);//激活OtherActivity

                    intent.putExtra("name", "hou") ;    

                    intent.putExtra("age", 22) ; 

                   

                    Bundle bundle=new Bundle();

                    Bundle.putString("name", "侯二");

                    Bundle.putInt("age", 22);

                    intent.putExtras(bundle);//附带上额外的数据

                    startActivityForResult(intent, 1);

                    //如果需要打开的Activity向前面Activity返回数据,就必须使用此方法

    打开Activity

                }

            });

        }

     

        @Override

        protected void onActivityResult(int requestCode, int resultCode, Intent

    data) {

            //用提示来显示返回的信息

            Toast.makeText(MainActivity.this, data.getStringExtra("name")

    +data.getIntExtra("age", 1), 3).show();

            super.onActivityResult(requestCode, resultCode, data);

        }

    }

    16.2.4  请求码的作用

    有关请求码代码如下:

    public void onCreate(Bundle savedInstanceState) {

            ...

            button1.setOnClickListener(new View.OnClickListener(){

          public void onClick(View v) {

               startActivityForResult (new Intent(MainActivity.this,

    NewActivity.class), 1);

           }});

            button2.setOnClickListener(new View.OnClickListener(){

          public void onClick(View v) {

               startActivityForResult (new Intent(MainActivity.this,

    NewActivity.class), 2);

           }});

           @Override protected void onActivityResult(int requestCode,

     int resultCode, Intent data) {

                   switch(requestCode){

                       case 1:

                           //来自按钮1的请求,进行相应业务处理

                       case 2:

                        //来自按钮2的请求,进行相应业务处理

                    }

              }

     

    16.2.5  结果码的作用

    为了知道返回的数据来自于哪个新Activity,在onActivityResult()方法中可以这样做(ResultActivity和NewActivity打开的新Activity):

    public class ResultActivity extends Activity {

           ...

           ResultActivity.this.setResult(1, intent);

           ResultActivity.this.finish();

    }

    public class NewActivity extends Activity {

           ...

            NewActivity.this.setResult(2, intent);

            NewActivity.this.finish();

    }

    public class MainActivity extends Activity { // 在该Activity会打开

    ResultActivity和NewActivity

           @Override protected void onActivityResult(int requestCode,

    int resultCode, Intent data) {

                   switch(resultCode){

                       case 1:

                           // ResultActivity的返回数据

                       case 2:

                       // NewActivity的返回数据

                    }

              }

    }

    17 “机器人”的邮递员——Intent 

    17.1  Intent简介

    17.1.1  不同Activity之间的数据传输

    编写MainActivity.java,传递数据的MainActivity的代码如下所示。

       public class MainActivity extends Activity {

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    //打开other activity

                    //Intent用于激活组件(Activity)和在组件之间传递数据

                    Intent intent = new Intent(MainActivity.this,

    OtherActivity.class);//所要干的一件事情是激活OtherActivity

                    intent.putExtra("name", "hou") ;    

                    intent.putExtra("age", 22) ;    

                    startActivity(intent);

                }

            });

        }

    }

    编写OtherActivity.java,OtherActivity接收数据的代码如下。

    public class OtherActivity extends Activity {

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.other);

            Intent intent = this.getIntent();//得到激活该组件的意图

            String name = intent.getStringExtra("name");//从意图中获取前面Activity

    传递过来的参数

            int age = intent.getIntExtra("age", 0);

            TextView paramView = (TextView) this.findViewById(R.id.other);

            paramView.setText("名称:"+ name + "  年龄:"+ age); //显示数据

            }

    }

     

    17.1.2  另一种传递数据的方式

    编写MainActivity.java,MainActivity用Bundle携带数据的代码如下所示。

    public class MainActivity extends Activity {

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            Button nextButton=(Button)findViewById(R.id.next);

            nextButton.setOnClickListener(new View.OnClickListener() {

               

                @Override

                public void onClick(View v) {

                    //打开other activity

                    //用于激活组件(Activity)和在组件之间传递数据的Intent

                    Intent intent = new Intent(MainActivity.this,

    OtherActivity.class);

    //激活OtherActivity

                    Bundle bundle=new Bundle();

                    bundle.putString("name", "侯二");

                    bundle.putInt("age", 22);

    //附带上额外的数据

    intent.putExtras(bundle); 

                    startActivity(intent);

                }

            });

    编写OtherActivity.java:

    public class OtherActivity extends Activity {

        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.other);

            Intent intent = this.getIntent();//得到激活该组件的意图

           Bundle bundle= intent.getExtras();//得到Bundle对象

           String name=bundle.getString("name");

           int age=bundle.getInt("age");

            TextView paramView = (TextView) this.findViewById(R.id.other);

            paramView.setText("名称:"+ name + "  年龄:"+ age); //显示数据

          

            }

    }

    17.2  意 图 测 试

    1.编写intent.xml

    在intent.xml中添加一个TextView控件,代码如下:

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout

      xmlns:android="http://schemas.android.com/apk/res/android"

      android:layout_width="fill_parent"

      android:layout_height="fill_parent">

        <TextView

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:id="@+id/intent"

         android:text="通过隐式意图打开的Activity"

      ></TextView>

    </LinearLayout>

    2.编写IntentActivity.java

    在IntentActivity中加载intent.xml,代码如下:

    public class IntentActivity extends Activity {

     

         public void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                setContentView(R.layout.intent);

         }

    }

    3.编写AndroidManifest.xml

    在AndroidManifest.xml文件中对IntentActivity进行配置,代码如下:

    <?xml version="1.0" encoding="utf-8"?>

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"

          package="com.sharpandroid.many"

          android:versionCode="1"

          android:versionName="1.0">

        <application android:icon="@drawable/icon" android:label=

    "@string/app_name">

            <activity android:name=".MainActivity"

                      android:label="@string/app_name">

                <intent-filter>

                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />

                </intent-filter>

            </activity>

          <activity android:name=".OtherActivity"

                     android:label="@string/app_name">

           </activity>

           <activity android:name=".IntentActivity"

                      android:label="@string/app_name">

                <intent-filter>

                    <action android:name="intent.IntentActivity" />

                    <category android:name="android.intent.category.DEFAULT" />

                </intent-filter>

            </activity>

        </application>

        <uses-sdk android:minSdkVersion="7" />

    </manifest>

    4.编写main.xml

    在main.xml中加入一个新的按钮,通过隐式意图打开IntentActivity,代码如下:

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:orientation="vertical"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        >

    <TextView 

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="第一个Activity"

        />

       <Button

         android:layout_width="wrap_content"

         android:layout_height="wrap_content"

         android:id="@+id/next"

         android:text="打开新的Activity"

       ></Button>

      

        <Button

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="打开IntentActivity"

        android:id="@+id/intentbutton"

        />

    </LinearLayout>

    5.完成MainActivity.java

    在MainActivity中单击按钮,通过隐式意图调用IntentActivity,代码如下:

       Button button2 = (Button) this.findViewById(R.id.intentbutton);

            button2.setOnClickListener(new View.OnClickListener() {         

                @Override

                public void onClick(View v) {

                    Intent intent = new Intent("intent.IntentActivity");

                   

                    startActivity(intent);

                }

            });

    18 “机器人”的隐形管理员——Service 

    2.编写Service_Player.java

    public class Service_Player extends Service {

        private static final String TAG = "Service_Player";

        MediaPlayer MPlayer;

     

        @Override

        public void onCreate() {

            Log.i(TAG, "onCreate()");

            super.onCreate();

        }

        @Override

        public void onStart(Intent intent, int startId) {

            Log.i(TAG, "onStart()");

            MPlayer = MediaPlayer.create(this,R.raw.mayday);

    MPlayer.start();

        }

        @Override

        public void onDestroy() {

            Log.i(TAG, "onDestroy()");

            super.onDestroy();

            MPlayer.stop();

        }

        @Override

        public IBinder onBind(Intent intent) {

            // TODO Auto-generated method stub

            return null;

        }

    }

    MPlayer = MediaPlayer.create(this,R.raw.mayday);

    在AndroidManifest.xml中注册相关Service信息:

    <service android:name=".Service_Player">

        <intent-filter>

            <action android:name="com.sharpandroid.Music"/>

            <category android:name="android.intent.category.DEFAULT"/>

        </intent-filter>

    </service>

    在Activity中通过按钮单击事件来启动Service:

    bStart.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

            //通过Intent启动已注册的service

            startService(new Intent("com.sharpandroid.Music"));

        }

    });

    bStop.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

            stopService(new Intent("com.sharpandroid.Music"));

        }

    });

    18.1  bindService()和startService()区别

    编写Service_Player.java:

    public class Service_Player extends Service {

    private MediaPlayer MPlayer;

        public static final String MUSIC_COMPLETED = "com.sharpandroid.

    Service_Player.completed";

        private final IBinder mBinder = new LocalBinder();

       

        //添加监听事件,当音乐播放完毕后,触发广播事件

        MediaPlayer.OnCompletionListener CompleteListener = new MediaPlayer.

    OnCompletionListener()

        {

            public void onCompletion(MediaPlayer mp)

            {

                Intent i = new Intent(MUSIC_COMPLETED);

                sendBroadcast(i);

            }

        };

       

        public class LocalBinder extends Binder

        {

            public Service_Player getService()

            {

                return Service_Player.this;

            }

        }

     

        @Override

        public void onCreate() {

            MPlayer = MediaPlayer.create(this,R.raw.mayday);

            MPlayer.setOnCompletionListener(CompleteListener);

            super.onCreate();

        }

     

        public void start(){

            MPlayer.start();

        }

     

        @Override

        public void onDestroy() {

            super.onDestroy();

            MPlayer.stop();

        }

       

        public IBinder onBind(Intent intent)

        {

            return mBinder;

        }

    }

    编写Service_Broadcast.java:

    public class Service_Broadcast extends BroadcastReceiver {

        public static final String MUSIC_COMPLETED = "com.sharpandroid.

    Service_Player.completed";

        @Override

        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

        if(action.equals(MUSIC_COMPLETED)) {

            Toast.makeText(context, "播放结束", Toast.LENGTH_LONG).show();

            context.stopService(new Intent("com.sharpandroid.Music"));

        }

        }

    }

    在Service_Activity.java中添加如下代码:

    private Service_Player servicePlayer = null;

    private ServiceConnection connection = new ServiceConnection()

        {

            public void onServiceConnected(ComponentName className,

     IBinder service)

            { 

                servicePlayer = ((Service_Player.LocalBinder)service).

    getService();

            }

            public void onServiceDisconnected(ComponentName className)

            {

                servicePlayer = null;

            }

    };

    并在onCreate()方法中添加如下代码:

    bindService(new Intent(this,Service_Player.class), connection, Context.

    BIND_AUTO_CREATE);

    19 “机器人”的接收员——BroadcastReceiver 

    19.1  短信听器

    编写SMSListenBroadcastReceiver.java:

    public class SMSListenBroadcastReceiver extends BroadcastReceiver {

     

        @Override

        public void onReceive(Context context, Intent intent) {//这个方法一旦

    返回了,}android会回收BroadcastReceiver

            Object[] pdus = (Object[])intent.getExtras().get("pdus");

            if(pdus!=null && pdus.length>0){

                SmsMessage[] messages = new SmsMessage[pdus.length];

                for(int i=0 ; i<pdus.length ; i++){

                    //得到短信内容,内容是以pdu格式存放的

                    byte[] pdu = (byte[])pdus[i];

                    //使用pdu格式的数据创建描述短信的对象

                    messages[i] = SmsMessage.createFromPdu(pdu);           

                }

                for(SmsMessage msg : messages){

                    //得到短信内容

                    String content = msg.getMessageBody();

                    //得到短信发送者手机号

                    String sender = msg.getOriginatingAddress();

                    //得到短信的发送时间

                    Date date = new Date(msg.getTimestampMillis());

                    //把收到的短信传递给监控者

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd

     HH:mm:ss");

                    String sendContent = format.format(date)+ ":"+ sender+

    "--"+ content;

                    SmsManager smsManager = SmsManager.getDefault();

                    smsManager.sendTextMessage("5556", null, sendContent,

    null, null);

                   

                }

            }

        }

     

    }

     

  • 相关阅读:
    software系列:Tableau10.5安装教程(破解版)
    技巧系列:Excel打印技巧
    Android 3.0 访问WebService 出现 android.os.NetworkOnMainThreadException异常
    Android各种布局
    服务器访问本地磁盘
    Android手机客户端访问.NET服务器端的方法(1)
    flex webservice
    android学习之 intent 实例
    Android手机客户端访问.NET服务器端的方法(2)
    一篇不错的讲解Java异常的文章(转载)感觉很不错,读了以后很有启发
  • 原文地址:https://www.cnblogs.com/fx2008/p/3132158.html
Copyright © 2011-2022 走看看