首页 > 解决方案 > Android Studio 广播编程

问题描述

我正在学习为 Android 开发应用程序,但我坚持这个话题:

https://www.tutorialspoint.com/android/android_broadcast_receivers.htm

我访问了许多带有示例的站点,下载了源代码,并在两台不同的计算机上使用 Android Studio 进行了尝试,并在虚拟和物理设备中进行了尝试,但我不知道问题出在哪里。

显现

<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/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <receiver android:name=".MyReceiver" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.AIRPLANE_MODE" />
            <action android:name="android.intent.action.TIME_TICK" />
            <action android:name="com.example.myapplication.TEST_BROADCAST" />
        </intent-filter>

    </receiver>
</application>

MyReceiver.java

公共类 MyReceiver 扩展 BroadcastReceiver{

String logPrefix = "Android : ";

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(logPrefix, "Broadcast received");
    Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}

}

MainActivity.java

公共类 MainActivity 扩展 AppCompatActivity {

String logPrefix = "Android : ";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(logPrefix, "The onCreate() event");
}


public void broadcastIntent(View view){
    Log.d(logPrefix, "Sending broadcast...");
    Intent intent = new Intent("com.example.myapplication.TEST_BROADCAST");
    sendBroadcast(intent);
}

}

标签: android-studioandroid-broadcastandroid-broadcastreceiver

解决方案


推荐阅读