BroadcastRecevier不想改变价值

时间:2015-04-09 17:58:03

标签: android broadcastreceiver android-broadcast

当我将数据从一个活动通过广播传递到第二个活动时以及当我第一次输入文本时,我遇到了这个问题 - 这一切都很好,但是当我回来并输入另一个文本时,最后一个文本保持不变。我在这里和那里放了吐司,看来Broadcastreceiver无法改变这个String值。

MainActivity:

public void setCall(int timeToCall){
    if (alarmManager!= null) {
        alarmManager.cancel(pendingIntent);
    }
    String name = e1.getEditableText().toString();
    //Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(MainActivity.this, ThisBroadcastReceiver.class);
    intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    intent.putExtra("name",name);
    pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + timeToCall, pendingIntent);
}

广播接收器:

@Override
public void onReceive(Context context, Intent intent) {
    String name = intent.getExtras().getString("name");

    Intent i = new Intent(context, CallScreen.class);
    i.setClassName("(package)", "(classname)");
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.putExtra("name2", name);
    context.startActivity(i);
    Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}

第二项活动:

public class CallScreen extends Activity {

TextView incomingCall, caller;
MediaPlayer mp;
String name;

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


    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        name = extras.getString("name2");
    }

    incomingCall = (TextView) findViewById(R.id.textIncomingView);
    caller = (TextView) findViewById(R.id.callerId);
    caller.setText(name);

    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mp = MediaPlayer.create(getApplicationContext(), notification);
    mp.start();
}

@Override
protected void onPause() {
    super.onPause();
    if (mp != null) {
        mp.release();
        mp = null;
    }
    finish();
}

@Override
protected void onStop() {
    super.onStop();
    if (mp != null) {
        mp.release();
        mp = null;
    }
    finish();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mp != null) {
        mp.release();
        mp = null;
    }
    finish();
}

1 个答案:

答案 0 :(得分:2)

Pending Intents缓存在Android中。如果要重用具有相同ID的待处理意图,则必须使用以下命令进行更新:

pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);