android之自定义广播

布局文件


点击按钮发送广播

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/sure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="发送广播"/>
</LinearLayout>
复制代码

activity


在Activity中监听按钮事件并创建意图对象,通过sendBroadcast将意图对象发送出去

复制代码
package xidian.dy.com.chujia;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    SharedPreferences sp;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sp = getSharedPreferences("hate", Context.MODE_PRIVATE);
        Button button = (Button) findViewById(R.id.sure);
        if(button != null)
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("com.dy.xd.test");
                    sendBroadcast(intent);
                }
            });
    }
}
复制代码

广播接收者


复制代码
package xidian.dy.com.chujia;

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

/**
 * Created by dy on 2016/7/12.
 */
public class Custom extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Toast.makeText(context, "我的广播" +action, Toast.LENGTH_SHORT).show();
    }
}
复制代码

清单文件


在清单文件中需要我们在创建意图对象时设置的action

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xidian.dy.com.chujia">
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="主界面">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".Custom">
        <intent-filter>
            <action android:name="com.dy.xd.test" />
        </intent-filter>
    </receiver>
</application>
</manifest>
复制代码

 

posted @   被罚站的树  阅读(226)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示