gpt4 book ai didi

android - 如何在 Oreo 中发送 BroadCast?

转载 作者:行者123 更新时间:2023-11-29 00:59:01 26 4
gpt4 key购买 nike

这是我的类(class),我正在从服务器获取通知->

 public class GCMListener_Service extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
Intent notificationReceived = new Intent("com.example.mypackage”);
notificationReceived.putExtra(“key", fromWhere);
sendBroadcast(notificationReceived);
}
}

这是我在 AndroidManifiestfile 中声明的:

<service
android:name="com.example.pushnotification.GCMListener_Service"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>

我在这里尝试获取通知:

public class PushMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Timber.d("Received push notification”);
}
}

这是我在 AndroidManifiest 文件中的接收器->

<receiver
android:name=".notification.PushMessageReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.example.mobile.pushnotification.notificationReceived" />
</intent-filter>
</receiver>

使用 android 8 (oreo) 下面的给定代码,它工作正常我在 onReceive 方法的 PushMessageReceiver 类中获取和接收通知消息,但在 android 中我无法获得通知无法发送广播任何人都可以建议我如何发送在 Android O 中广播。

最佳答案

在您的 Application 类中注册和取消注册类,如下所示:

    public class YourProjectApplication extends MultiDexApplication {
private static YourProjectApplication sInstance;



public static YourProjectApplication getInstance() {
return sInstance;

}

@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}

public void registerInternetConnectivityBroadCast(){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(appInternetStatus, intentFilter);

}

public void unSetConnectivityListener(AppInternetStatus.InternetConnectivityReceiverListener listener) {
try {
unregisterReceiver(appInternetStatus);
}catch (Exception e){
e.printStackTrace();
}

try {
AppInternetStatus.internetConnectivityReceiverListener = listener;
}catch (Exception e){
e.printStackTrace();
}
}

然后在您的 mainActivity 类(也可以是您的基类)中像这样调用您的广播 receiver:

 getInstance().registerBroadCast();
getInstance().setConnectivityListener(this);

为了注销您的通知。在您的主要 Activity 类的 onPause() 方法中:

@Override
protected void onPause() {
super.onPause();
getInstance().unSetConnectivityListener(null);
}

关于android - 如何在 Oreo 中发送 BroadCast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52473380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com