alltolove 发表于 2017-10-10 10:42:40

android 手机编程5.4

发送有序广播就是把sendBroadcast()语句改成sendOrderedBroadcast()就行了,太简单这里就不说了。下面说一下本地广播,就是程序自己只给自己发送的广播,其他程序收不到。为了省事我们从新建个项目,然后把布局文件添加个按钮,就是把activity_main.xml文件修改成<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xinwei.localbroadcast.MainActivity">

    <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="sent local broadcast"/>


</android.support.constraint.ConstraintLayout>

然后修改mainactivity.java文件,在这个文件里写了个内部类用于接收广播,就不再另写一个文件了package com.example.xinwei.localbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private LocalReceiver localreceiver;
    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      localBroadcastManager = LocalBroadcastManager.getInstance(this);
      Button button=(Button)findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("alltolove.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
      });
      intentFilter=new IntentFilter();
      intentFilter.addAction("alltolove.LOCAL_BROADCAST");
      localreceiver=new LocalReceiver();
      localBroadcastManager.registerReceiver(localreceiver,intentFilter);
    }
    class LocalReceiver extends BroadcastReceiver{

      @Override
      public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
      }
    }

    @Override
    protected void onDestroy() {
      super.onDestroy();
      localBroadcastManager.unregisterReceiver(localreceiver);
    }
}

效果图为:
页: [1]
查看完整版本: android 手机编程5.4