关于android:extra 不通过intent

extra doesn't pass through intent

我正在尝试将 Alarm_no 传递给 alarm_Time.java,当警报启动时,我可以取消它并通过意图获取 Alarm_no
警报被取消,但 Alarm_no 没有通过,并且 pending_intent 为空,我不知道为什么以及如何解决这个问题?

MainActivity2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
public class MainActivity2 extends AppCompatActivity {
TextView update_txt;
TextView info_txt;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar); ///
    this.context = this ;

    update_txt = (TextView) findViewById(R.id.update_txt);
    info_txt = (TextView) findViewById(R.id.info_txt);

    final int[] h = {23, 23};
    final int[] m = {21, 22};
    final int length = h.length;

    final Intent[] intent = new Intent[length];
    final Calendar[] cal = new Calendar[length];
    final AlarmManager[] alarmManager = new AlarmManager[length];
    final PendingIntent[] pending_intent = new PendingIntent[length]; ;

    for(int i =0; i<length; i++) {
        cal[i] = Calendar.getInstance();
        cal[i].set(Calendar.HOUR_OF_DAY, h[i]);
        cal[i].set(Calendar.MINUTE, m[i]);
        if (cal[i].getTimeInMillis() < System.currentTimeMillis())
        {    cal[i].add(Calendar.DAY_OF_MONTH, 1);  }

        intent[i] = new Intent(this.context, AlarmReceiver.class);
        alarmManager[i] = (AlarmManager) getSystemService(ALARM_SERVICE);

    }
    Button alarm_on = (Button) findViewById(R.id.alarm_on);
    alarm_on.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String h1_string = String.valueOf(h[0]);
            String m1_string = String.valueOf(m[0]);


            for(int i =0; i<length; i++) {


                set_alarm_text("Alarm on!" + h1_string +":" + m1_string);

                intent[i].putExtra("extra","alarm on");
                intent[i].putExtra("Alarm_no", i);
                pending_intent[i] = PendingIntent.getBroadcast(MainActivity2.this, i, intent[i], PendingIntent.FLAG_UPDATE_CURRENT );
                alarmManager[i].set(AlarmManager.RTC_WAKEUP, cal[i].getTimeInMillis(), pending_intent[i]);

            }


        }
    });

    //intialize alarm_off button
    Button alarm_off = (Button) findViewById(R.id.alarm_off);
    // create on click listner to end alarm
    alarm_off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle extras = getIntent().getExtras();
            int alarm_No = -1;
            if (extras != null) {
                 alarm_No = extras.getInt("alarm_No2");
            }

            Log.v("help", String.valueOf(alarm_No));

            //method that change update_txt txtbox
            set_alarm_text("Alarm off!");
            //cancel the alarm
            alarmManager[0].cancel(pending_intent[0]);
            // put extra string into my_intent
            // tells the clock that you pressed the"alarm off" button
            intent[0].putExtra("extra","alarm off");
            // stop the ringtone
            sendBroadcast(intent[0]);
        }
    });
}

private void set_alarm_text(String output) {
    update_txt.setText(output);
}

private void set_info_text(String output) {
    info_txt.setText(output);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}}

报警接收器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Log.e("We are in the receiver","Yay");

     //fetch extra strings from the intent   >>>  get_ur_string =extra //   alarm on - alarm off
    String get_ur_string = intent.getExtras().getString("extra");
    int No = intent.getIntExtra("Alarm_no",-1);


  //  Log.e("What is the key?", get_ur_string);


    //create an intent to the ringtone service
    Intent service_intent = new Intent(context, RingtonePlayingService.class);

    // pass the extra from Main Activity to Ringtone Playing Service
    service_intent.putExtra("extra", get_ur_string);
    service_intent.putExtra("Alarm_no", No);

    //start the ringtone services
    context.startService(service_intent);



}}

铃声播放服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class RingtonePlayingService extends Service {

MediaPlayer media_song;
int startId;
boolean isRunning;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.i("LocalService","Received start id" + startId +":" + intent);
    // fetch the extra string values
    String state = intent.getExtras().getString("extra");
    int No = intent.getIntExtra("Alarm_no", -2);
     Log.e("Ringtone state:extra", state);
    // notification
    // set up the notification service
    NotificationManager notify_manager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
    // set up an intent that goes to the Main Activity
    Intent intent_main_activity = new Intent(this.getApplicationContext(), alarm_Time.class);
    intent.putExtra("extra","alarm on");
    intent.putExtra("Alarm_no", No);
    // set up a pending intent
    PendingIntent pending_intent_main_activity = PendingIntent.getActivity(this, No,
            intent_main_activity, PendingIntent.FLAG_UPDATE_CURRENT);
    // make the notification parameters
    Notification notification_popup = new Notification.Builder(this)
            .setContentTitle("An alarm is going off!")
            .setContentText("Click me!")
            .setSmallIcon(R.drawable.image)
            .setContentIntent(pending_intent_main_activity)
            .setAutoCancel(true)
            .build();
    // set up notification atart command
    notify_manager.notify(0, notification_popup);
    // this converts the extra strings from the intent to start IDs, values 0 or 1
    assert state != null;
    switch (state) {
        case"alarm on":
            startId = 1;
            int alarm_num = intent.getExtras().getInt("No");
            break;
        case"alarm off":
            startId = 0;
            Log.e("Start ID is", state);
            break;
        default:
            startId = 0;
            break;
    }
    // if else statments
    // if there is no music playing, and the user pressing"alarm on"
    // music should start playing
    if( !this.isRunning && startId == 1  ){
        Log.e("there is no music","and u want start");
        // create an instant of the media player
        media_song = MediaPlayer.create(this, R.raw.tone);
        // start the ringtone
        media_song.start();
        this.isRunning = true;
        this.startId = 0;

    }
    // if there is music playing, and the user pressing"alarm off"
    // music should stop playing
    else  if( this.isRunning && startId == 0 ){
        Log.e("there is  music","and u want stop");

        // stop the ringtone
        media_song.stop();
        media_song.reset();
        this.isRunning = false;
        this.startId = 0;

    }
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    //tell the user we stopped
    Log.e("on Destroy called","ta da");

    super.onDestroy();
    this.isRunning = false;

}}

alarm_Time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class alarm_Time extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm__time);
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view,"Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    //  final Intent intent ;
    final AlarmManager alarmManager ;
    final PendingIntent pending_intent ;
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    // intent = new Intent(this.context, RingtonePlayingService.class);
    final Intent intent = new Intent(this, AlarmReceiver.class);
    int No = getIntent().getIntExtra("Alarm_no", -20);
   int No1 = intent.getIntExtra("Alarm_no",-5);
   Log.v("see", String.valueOf(No));
   Log.v("see1", String.valueOf(No1));

    pending_intent = PendingIntent.getBroadcast(alarm_Time.this,No, intent, PendingIntent.FLAG_NO_CREATE);
    if (pending_intent == null) {
        Log.v("help","PendingIntent is null");
    }
    else {
        Log.v("help","PendingIntent is not null");
    }
    //intialize alarm_off button
    Button alarm_off = (Button) findViewById(R.id.alarm_off);
    // create on click listner to end alarm
    //final Intent finalIntent = intent;
    alarm_off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //method that change update_txt txtbox
                              // set_alarm_text("Alarm off!");
            //cancel the alarm
            alarmManager.cancel(pending_intent);
            // put extra string into my_intent
            // tells the clock that you pressed the"alarm off" button
            intent.putExtra("extra","alarm off");
            // stop the ringtone
            sendBroadcast(intent);
        }
    });
}}


这是您服务的 onStartCommand():

中的代码

1
2
3
4
5
// set up an intent that goes to the Main Activity
Intent intent_main_activity = new Intent(this.getApplicationContext(),
                                       alarm_Time.class);
intent.putExtra("extra","alarm on");
intent.putExtra("Alarm_no", No);

你想把"附加"放在 intent_main_activity 而不是 intent 中。