Android 学习笔记2

全屏显示

//在 SetContentView 前加上下面代码
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


Handle 信息处理机制

  • 由于 Android 平台不允许 Activity 新开启的线程访问该Activity里的界面组件,这样就会导致新启动的线程无法动态改变界面组件的属性值。这时可以用Handler的消息传递机制来处理
package com.example.androidtest;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    Timer timer1 = new Timer();
    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Handler myHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                //如果本消息是该程序发送的,则执行下面步骤
                if(msg.what == 0x1233)
                {
                    /*
                     * 这里可以编写改变界面布局的代码,
                     * 由下面的Timer 定时间动态发送    msg.what = 0x1233;
                     * 发送完则调用handleMessage函数
                     * handlerMessage 识别到    0x1233,说明是本程序发送的消息
                     * 则执行下面步骤        
                     */
                    Log.v("test", " test:" + (i++));
                }
            }

        };

        timer1.schedule(new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Message msg = new Message();
                //定义识别标志0x1233
                msg.what = 0x1233;
                myHandler.sendMessage(msg);
            }
        }, 0, 800);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


Android 的声明生命机制


  • 活动状态:当前Activity位于前台,用户可见,可以获得焦点
  • 暂停状态:其他Activity位于前台,该Activity依然可见,只是不能获得焦点
  • 停止状态:该Activity不可见,失去焦点
  • 销毁状态:该Activity结束,或Activity所在Dalvik进程被结束

使用SharedPreferences对数据进行读取


  • 该方法进行数据的读取和存储操作允许的数据量比较少,使用的是键值对,即key-value
  • 使用方法如下:
//声明对象
SharedPreferences preferences;
SharedPreferences.Editor editor;
preferences = getSharedPreferences("example",MODE_PRIVATE);
editor = preferences.edit();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日"+"hh:mm:ss");
//存数据
editor.putString("time", sdf.format(new Date()));
editor.putInt("random", (int)(Math.random()*100));
editor.commit();
//取数据
String time = preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);

package com.example.androidtest;

import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*
         * MODE_PRIVATE表示被该应用程序读
         * MODE_WORLD_READABLE 表示数据可以被其他应用程序读,但不能被其他应用程序写
         * MODE_WORLD_WRITEABLE 表示数据可以被其他应用程序写
         */
        preferences = getSharedPreferences("example",MODE_PRIVATE);
        editor = preferences.edit();
        Button read = (Button)findViewById(R.id.read);
        Button write = (Button)findViewById(R.id.write);
        read.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //取数据
                String time = preferences.getString("time", null);
                int randNum = preferences.getInt("random", 0);
                String result = time == null ? "您还没存入数据!":"写入时间为"+time+"\n 上次生成的随机数为:"+randNum;
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            }
        });

        write.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //格式化数据
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日"+"hh:mm:ss");
                //存数据
                editor.putString("time", sdf.format(new Date()));
                editor.putInt("random", (int)(Math.random()*100));
                editor.commit();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


Bundle 类存键值对数据


  • Bundle类是一个key-value对,两个Activity之间的通讯可以通过Bundle类来实现
//发送数据的Activity
//新建一个Bundle类
Bundle bundle = new Bundle();
//Bundle类中加入数据(key- value的方式,另一个activity获取数据时需要key)
bundle.putString("first", "第一个BroadCastReceive 存入的消息");
//新建一个intent对象,并将该bundle加入这个intent对象
Intent  intent = new Intent();
intent.putExtras(bundle);
intent.setClass(FirstActivity.this,SecondActivity.class);
startAtivity(intent);

//接收数据的Activity
Bundle bundle = getIntent().getExtras();
//读出数据
String data = bundle.getString("first");


Broadcast 广播接收

  • BroadcastReceiver 本质上就是一种全局的监听器,用于监听系统全局的广播消息
  • 之前介绍的各种 OnClickListener 只是程序级别的监听器,这些监听器运行在制定程序中,当程序退出时,这些监听器也就关闭了,而BroadcastReceiver属于系统级别的监听器,拥有自己的进程,只要存在与之匹配的Intent被广播出来,BroadcastReceiver总会被激发
  • BroadcastReceiver本质上属于一个监听器,因此其实现方法只要重写BroadcastReceiveronReceive方法即可
  • 一旦实现了BroadcastReceiver,就应该知道那个该BroadcastReceiver能匹配的Intent,可在AndroidManifest.xml中配置
<receiver android:name=".MyReceiver">
    <intent-filter >
        <action android:name="llp"/>
    </intent-filter>
</receiver>


  • 每次系统Broadcast 事件发生后,系统就会创建对应的BroadcastReceiver实例,并自动触发它的onReceive()方法,onReceive()方法执行完后,BroadcastReceiver实例就会被销毁,若onReceive()方法不能再10s内执行完成,Android就会认为该线程无响应
  • BroadCast JAVA 代码
package com.example.androidtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button send = (Button)findViewById(R.id.read);
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                //这里要跟AndroidMainfest里面的 action 的 name 一样
                //action name 最好包含包名
                intent.setAction("llp");
                intent.putExtra("msg", "simple message");
                sendBroadcast(intent);
            }
        });
    }
}


  • Override onReceiver()方法 MyReceive.java文件
package com.example.androidtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, 
                "接收到的Intent的Action为:"+intent.getAction()+"\n消息内容为:"+intent.getStringExtra("msg"), 5000).show();
    }
}


两种BroadCast
  • BroadCast 被分为两种:
    1. Normal BroadCast:完全异步,可以在同一时刻上被所有的接受者接收到,但接受者无法将信号处理结果发给下一个接受者,也无法终止BroadCast Intent的传播
    2. Ordered BroadCast:设置优先级 android:priority,该数值越高,表示优先级越高,可以网下一个优先级的接受者发送数据,也就可以实现接受者将数据处理后发送给下一个接受者,同时可以实现终止BroadCast Intent的传播
//优先接收者将将数据存入 BroadCast 中
Bundle bundle = new Bundle();
bundle.putString("first", "第一个BroadCastReceive 存入的消息");
setResultExtras(bundle);
//终止BroadCast Intent 的传播
// abortBroadcast();

//下一个接受者获取数据
Bundle bundle = getResultExtras(true);
String first = bundle.getString("first");


  • XML 中代码申明代码如下:

<receiver 
    android:name=".MyReceiver">
    <!-- 注明优先级为20 -->
    <intent-filter android:priority="20" >
        <action android:name="llp"/>
    </intent-filter>
</receiver>
<receiver 
    android:name=".MyReceiver2">
    <!-- 注明优先级为0 ,范围为:-1000:1000 -->
    <intent-filter android:priority="0">
        <action android:name="llp"/>
    </intent-filter>
</receiver>

 


  • 完整代码如下:
//发送广播代码
package com.example.androidtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button send = (Button)findViewById(R.id.read);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setAction("llp");
                intent.putExtra("msg", "simple message");
                //发送有序广播
                sendOrderedBroadcast(intent, null);
            }
        });
    }
}

//高优先级接受者
package com.example.androidtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(context, 
                "接收到的Intent的Action为:"+intent.getAction()+"\n消息内容为:"+intent.getStringExtra("msg"), 5000).show();
        Bundle bundle = new Bundle();
        bundle.putString("first", "第一个 BroadCastReceive 存入的消息");
        //处理消息并传递给下一个接收者
        setResultExtras(bundle); 
        abortBroadcast();
    }
}

//低优先级接受者
package com.example.androidtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyReceiver2 extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        //获取数据
        Bundle bundle = getResultExtras(true);
        String first = bundle.getString("first");
        Toast.makeText(context, "第一个BroadCastRecver 存入的消息为:"+first,     5000).show();
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值