android 广播接收器推送通知

6ss1mwsb  于 2022-12-02  发布在  Android
关注(0)|答案(2)|浏览(127)

我已经在我的android应用中实现了推送通知:
在我的主课堂上:

// PUSH
Parse.initialize(this, applicationId, clientKey); 
PushService.setDefaultPushCallback(this, SlidingMenuActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
ParseAnalytics.trackAppOpened(getIntent());

在我的manifest.xml中:

<!-- PUSH -->
<service android:name="com.parse.PushService" />

<receiver android:name="com.parse.ParseBroadcastReceiver" >
    <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
          <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

当我打开我的应用程序,我收到通知。我点击返回并关闭应用程序。我仍然收到通知约1小时。一小时后,我发送了三个通知,没有通知出现。所以我重新启动我的应用程序,并出现三个通知通知。
我猜我的广播接收器已经被重新创建了。为什么我的机器人正在杀死我的通知广播接收器?
我该怎么补救?

qv7cva1a

qv7cva1a1#

尝试我解决方案,它对我很有效:将广播接收器链接到服务,方法是添加

public void onReceive(Context context, Intent intent) {
    //add the following
    Intent e = new Intent(context, urservice.class);
    context.startService(e);
}

然后在服务onCreate()中注册接收器,如下所示

@Override
public void onCreate() {
    super.onCreate();
    IntentFilter filter = new IntentFilter(Intent.BOOT_COMPLETED);
    filter.addAction(Intent.USER_PRESENT);
    BroadcastReceiver mReceiver = new ParseBroadcastReceiver();
    registerReceiver(mReceiver, filter);
}

然后从清单中删除您的“broadcastreceiver”,最后,您肯定希望服务尽可能长时间地生存,,那么您还需要在int onStartCommand中为服务添加2个代码(Intent intent、int flags、int startId),确保您将以下内容

mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent bIntent = new Intent(urservice.this, urmain.class);       
    PendingIntent pbIntent = PendingIntent.getActivity(urservice.this, 0 , bIntent, 0);

    NotificationCompat.Builder bBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("title")
                .setContentText("sub title")
                .setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pbIntent);
    barNotif = bBuilder.build();
    this.startForeground(1, barNotif);
// also the following code is important 
return Service.START_STICKY;

现在在你的onstart命令的末尾设置return sticky。
希望我能帮上忙,祝你好运

bvhaajcl

bvhaajcl2#

你的设备会进入睡眠状态吗?它的内存会变低吗?所有这些你都必须考虑。你可能必须持有一个唤醒锁或启动一个服务,该服务返回一个值以重新启动sticky。

相关问题