广播接收器和待定意图:显示祝酒词

时间:2016-05-05 14:00:44

标签: android android-intent broadcastreceiver alarmmanager

以下是必须点击BroadCast Receiver的警报代码:

Intent intentWithData = new Intent(context, TokenActivity.class);
intentWithData.putExtra(Constants.ID,id);
intentWithData.putExtra(Constants.POSITION, finalI);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 007, intentWithData, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);

Broadcast receiver的代码是

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

public class TokenBroadcastReceiver extends BaseBroadCastReceiver {

String Id;
int position;
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Create a toast", Toast.LENGTH_SHORT).show();
}
}

清单是:

<receiver android:name=".broadcastReceiver.TokenBroadcastReceiver"/>

吐司没有露面。这个代码我哪里错了?

2 个答案:

答案 0 :(得分:10)

你混合了2件事。 如果您希望接收者获得意图:

Intent intentWithData = new Intent(context, TokenBroadcastReceiver.class);
intentWithData.putExtra(Constants.ID,id);
intentWithData.putExtra(Constants.POSITION, finalI);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 7, intentWithData, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);

如果您希望自己的活动获得意图:

Intent intentWithData = new Intent(context, TokenActivity.class);
intentWithData.putExtra(Constants.ID,id);
intentWithData.putExtra(Constants.POSITION, finalI);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 7, intentWithData, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);

另外,请确保您的接收器已在AndroidManifest.xml中注册

答案 1 :(得分:2)

您正在设置待处理意图,以根据您的代码打开活动

Intent intentWithData = new Intent(context, TokenActivity.class);

并在广播接收器中显示吐司。请更正您的代码,它将开始工作。

    Intent intentWithData = new Intent(this, TokenBroadcastReceiver.class);
    intentWithData.putExtra("id",5);
    intentWithData.putExtra("position", 4);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 007, intentWithData, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);

不要忘记在清单中注册您的广播

<receiver android:name=".broadcastReceiver.TokenBroadcastReceiver"/>