Broadcast组件——收发广播应用——收发静态广播

===========================================================================================

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">

    <Button
        android:id="@+id/btn_send_shock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="发送震动广播"
        android:textColor="@color/black"
        android:textSize="17sp" />

</LinearLayout>

 

代码:

package com.example.myapplication;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.receiver.ShockReceiver;


public class MainActivity extends AppCompatActivity implements View.OnClickListener
{

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


        findViewById(R.id.btn_send_shock).setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        if (v.getId() == R.id.btn_send_shock)
        {
            // Android8.0之后删除了大部分静态注册,防止退出App后仍在接收广播,
            // 为了让应用能够继续接收静态广播,需要给静态注册的广播指定包名。
            String receiverPath = "com.example.myapplication.receiver.ShockReceiver";

            Intent intent = new Intent(ShockReceiver.SHOCK_ACTION); // 创建一个指定动作的意图

            // 发送静态广播之时,需要通过setComponent方法指定接收器的完整路径
            ComponentName componentName  = new ComponentName(this, receiverPath);

            intent.setComponent(componentName); // 设置意图的组件信息

            sendBroadcast(intent); // 发送静态广播

            Toast.makeText(this, "已发送震动广播", Toast.LENGTH_SHORT).show();
        }
    }
}

 

ShockReceiver:
package com.example.myapplication.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.util.Log;

public class ShockReceiver extends BroadcastReceiver
{
    private static final String TAG = "ShockReceiver";

    // 静态注册时候的action、发送广播时的action、接收广播时的action,三者需要保持一致
    public static final String SHOCK_ACTION = "com.example.myapplication.receiver.ShockReceiver";


    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.d(TAG, "onReceive");
        if (intent.getAction().equals(ShockReceiver.SHOCK_ACTION))
        {
            // 从系统服务中获取震动管理器
            Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            
            vb.vibrate(500); // 命令震动器吱吱个若干秒,这里的500表示500毫秒
        }
    }

}

mainifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.VIBRATE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".receiver.ShockReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.myapplication.receiver.ShockReceiver" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Android Studio Broadcast 广播监听收发信息的源码示例: 1. 在 AndroidManifest.xml 文件中添加以下代码,声明需要监听的广播: ```xml <receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> </intent-filter> </receiver> ``` 2. 创建一个继承 BroadcastReceiver 的类 MyBroadcastReceiver,并在其 onReceive 方法中处理广播事件: ```java public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { Toast.makeText(context, "Boot completed", Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) { Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) { Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show(); } } } ``` 3. 在需要发送广播的地方调用以下代码: ```java Intent intent = new Intent("com.example.broadcast.MY_BROADCAST"); intent.putExtra("message", "Hello World"); sendBroadcast(intent); ``` 4. 在需要接收广播的地方注册广播接收器: ```java IntentFilter intentFilter = new IntentFilter("com.example.broadcast.MY_BROADCAST"); MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(); registerReceiver(myBroadcastReceiver, intentFilter); ``` 注意:在不需要接收广播时,一定要记得取消注册广播接收器,否则会造成内存泄漏: ```java unregisterReceiver(myBroadcastReceiver); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值