• Android总结六(BroadcastReceiver、通知、对话框、下拉列表)


    一、接收广播消息

      1.什么是BroadcastReceiver?

        BroadcastReceiver是Android系统四大组件之一,本质上就是一种全局的监听器,用于监听系统全局的广播消息。

      2.怎样创建BroadcastReceiver?

        1)创建一个类继承自BroadcastReceiver类;

        2)在AndroidManifest.xml配置<receiver>节点信息。

      3.一旦实现了BroadcastReceiver,接下来就应该制定该BroadcastReceiver能匹配的Intent,此时有两种方式。

        1)在AndroidManifest.xml文件中配置,这种方式会一直监听。例如如下代码: 

            <receiver android:name="com.gnnuit.smsreceiver.SmsReceiver" >
                <intent-filter android:priority="1000" >
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>

        2)使用代码进行指定,调用BroadcastReceiver的Context的registerReceiver(BroadcastReceiver receiver, IntentFilter filter)方法指定,这种方式可以通过unregisterReceiver(BroadcastReceiver receiver)取消监听,也叫临时监听。例如如下代码:

         IntentFilter filter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
            registerReceiver(new SmsReceiver(), filter);

      4.如果BroadcastReceiver的onReceive()方法不能在10秒内执行完成,Android会认为该程序无响应。所以不要在BroadcastReceiver的onReceive()方法里执行一些耗时的操作,否则会发生ANR异常。如果确实需要根据Broadcast来完成一些耗时的操作,则可以考虑通过Intent启动一个Service来完成该操作。不应考虑使用新线程去完成耗时操作,因为Broadcast本身的生命周期很短。

      5.Broadcast被分为如下两种:

        1)Normal Broadcast(普通广播):普通广播是完全异步的,可以在同一时刻(逻辑上)被所有接收者接收到,消息传递的效率比较高。但缺点是接收者不能将处理结果传递给下一个接收者,并且无法终止Broadcast Intent的传播。

        2)Ordered Broadcast(有序广播):有序广播的接收者将按预先声明的优先级依次接收Broadcast。优先级别声明在<intent-filter/>元素的android:priority属性中,数越大优先级别越高,取值范围为-1000-1000.有序广播可以调用abortBroadcast()方法终止Broadcast Intent的传播,Broadcast Intent的传播一旦终止,后面的接收者就无法接收到Broadcast。

      6.用于发送广播的两个方法:

        1)sendBroadcast():发送普通广播。

        2)sendOrderedBroadcast():发送有序广播。

      7.短信拦截实例

    SmsReceiver.java

    package com.gnnuit.smsreceiver;
    
    import java.util.Date;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.SmsMessage;
    
    public class SmsReceiver extends BroadcastReceiver {
    
        // 当接收到短信时被触发
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("接收到短信!!!");
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");// 通过pdus可以获得接收到的所有短信消息
            for (Object pdu : pdus) {
                SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
                String content = message.getMessageBody();// 获得短信内容
                String number = message.getOriginatingAddress();// 获得短信号码
                Date date = new Date(message.getTimestampMillis());// 获得短信日期
                System.out.println(number + "," + content + "," + date);
                if ("110".equals(number)) {
                    abortBroadcast();// 取消广播,让系统收不到短信
                }
            }
        }
    
    }

    AndroidManifest.xml

         <receiver android:name="com.gnnuit.smsreceiver.SmsReceiver" >
                <intent-filter android:priority="1000" >
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>

    二、通知

      1.吐司通知  

    Toast.makeText(getApplicationContext(), "吐司通知", Toast.LENGTH_SHORT).show();

      2.状态栏通知

         NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 创建通知管理器
            Intent intent = new Intent(this, StatebarActivity.class);
            PendingIntent pendingIntent = createPendingResult(100, intent, PendingIntent.FLAG_ONE_SHOT);
            //创建通知对象,设置
            Notification notification = new Notification.Builder(this)
                .setContentTitle("下载完成")
                .setContentText("QQ下载完成")
                .setSmallIcon(R.drawable.a)
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .build();
            //设置通知点击一次后自动清除
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            //用管理器发送通知
            manager.notify(0, notification);

      3.普通对话框

    OnClickListener listener=new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String msg="";
                    switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        msg="确定";
                        break;
                    case DialogInterface.BUTTON_NEGATIVE:
                        msg="取消";
                        break;
                    case DialogInterface.BUTTON_NEUTRAL:
                        msg="稍后";
                        break;
    
                    default:
                        break;
                    }
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            };
            new AlertDialog.Builder(this)
                .setTitle("是否下载更新")
                .setMessage("1.速度更快
    2.更多功能
    3.修复上个版本的Bug")
                .setPositiveButton("确定", listener)
                .setNegativeButton("取消", listener)
                .setNeutralButton("稍后", listener)
                .show();

       4.单选对话框

    final String[] items={"Java",".Net","PHP","网页平面设计","IOS","C++"};
            OnClickListener listener=new OnClickListener() {
                private int selected;
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        Toast.makeText(getApplicationContext(), items[selected], Toast.LENGTH_SHORT).show();
                        break;
    
                    default:
                        selected=which;
                        break;
                    }
                }
            };
            new AlertDialog.Builder(this)
                .setTitle("选择要学习的课程")
                .setSingleChoiceItems(items, -1, listener)
                .setPositiveButton("确定", listener)
                .show();

       5.多选对话框

         final String[] items={"吃饭","睡觉","打豆豆"};
            final boolean[] checkedItems={false,false,false};
            OnMultiChoiceClickListener choiceListener=new OnMultiChoiceClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if(isChecked){
                        System.out.println(items[which]);
                    }
                }
            };
            OnClickListener buttonListener=new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        StringBuffer sb=new StringBuffer();
                        for(int i=0;i<checkedItems.length;i++){
                            if(checkedItems[i]){
                                sb.append(items[i] + " ");
                            }
                        }
                        Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show();
                        break;
    
                    default:
                        break;
                    }
                }
            };
            new AlertDialog.Builder(this)
                .setTitle("请选择您的爱好")
                .setMultiChoiceItems(items, checkedItems, choiceListener)
                .setPositiveButton("确定", buttonListener)
                .show();

       6.进度对话框

           final ProgressDialog dialog= new ProgressDialog(this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setTitle("下载进度");
            dialog.setMax(100);
            dialog.setCancelable(false);
            new Thread(){
                public void run() {
                    for(int i=0;i<100;i++){
                        dialog.setProgress(i);
                        SystemClock.sleep(300);
                    }
                    dialog.dismiss();
                };
            }.start();
            dialog.show();

       7.下拉列表

         Spinner spinner=(Spinner) findViewById(R.id.spinner1);
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter.add("Java");
            adapter.add(".Net");
            adapter.add("PHP");
            adapter.add("网页平面设计");
            adapter.add("IOS");
            spinner.setAdapter(adapter);
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String selection=(String) parent.getItemAtPosition(position);
                    Toast.makeText(getApplicationContext(), selection, Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

       8.自动完成文本框

         AutoCompleteTextView actv=(AutoCompleteTextView) findViewById(R.id.at);
            String[] items={"tom","txt","terry","杨晓霞","杨名","杨真真"};
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items);
            actv.setAdapter(adapter);

      9.菜单

    @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;
        }
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.qq:
                Toast.makeText(getApplicationContext(), "分享到QQ", Toast.LENGTH_SHORT).show();
                break;
            case R.id.sina:
                Toast.makeText(getApplicationContext(), "分享到新浪", Toast.LENGTH_SHORT).show();
                break;
            case R.id.tt:
                Toast.makeText(getApplicationContext(), "分享到腾讯", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
            }
            return super.onOptionsItemSelected(item);
        }
        
  • 相关阅读:
    os.path.split()、os.path.realpath()和os.path.join()
    我终于也有了自己的博客网站
    (Bug修复)C#爬虫,让你不再觉得神秘
    DevExpress弹框、右键菜单、Grid的使用
    Linux 宝塔部署 ASP.NET Core 应用
    C#高级特性(反射)
    WPF 的内部世界(Binding)
    WPF 的内部世界(控件与布局)
    Layui事件监听(表单和数据表格)
    (待更新)tensorboard [Fatal error in launcher: Unable to create process using]
  • 原文地址:https://www.cnblogs.com/FlySheep/p/3850189.html
Copyright © 2020-2023  润新知