如何在android中获取broadcastreceiver的id

时间:2012-12-07 19:27:52

标签: android broadcastreceiver alarmmanager android-pendingintent

我希望获得 broadcastriver 的ID。

有没有办法找到 id broadcastreciver?我正在制作闹钟应用,在保存闹钟时,我使用broadcast发送pending intent。现在,如果用户编辑了警报,我想中止该特定broadcast并发送新时间的新broadcast

我该怎么做????

我正在使用此代码进行广播

Intent intent = new Intent(this, StartProfileBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, StartTimemill, pendingIntent);

在清单中,我使用此代码注册我的Broadcastreciver

 <receiver android:name="StartProfileBroadcastReceiver" >
 </receiver>

2 个答案:

答案 0 :(得分:4)

你可以通过这个项目找到我github上的项目,你可以发出很多警报,并可以捕捉到标记的警报。

需要警报类才能获取特定数据

Alarm.java

public class Alarm {
    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public int getUniqueID() {
        return uniqueID;
    }

    public void setUniqueID(int uniqueID) {
        this.uniqueID = uniqueID;
    }

    private int state;
    private int uniqueID;

}

AlarmHolder是单身,并将警报保存在arraylist中

<强> AlarmHolder.java

import java.util.ArrayList;

public class AlarmHolder{
      private static AlarmHolder uniqueAlarmHolder;   
      private ArrayList<Alarm> lAlarms;

      private AlarmHolder() {         
          lAlarms = new ArrayList<Alarm>();
      }

      public  synchronized static AlarmHolder getInstance()     
      {
          if (uniqueAlarmHolder == null) {
              uniqueAlarmHolder = new AlarmHolder();
            }
            return uniqueAlarmHolder;
      }   

      public void registerAlarm(int id) {
          Alarm a = new Alarm();
          a.setState(1);
          a.setUniqueID(id);

          lAlarms.add(a);
        }

      public void removeAlarm(int id,Alarm a) {
          Alarm newAlarm = new Alarm();
          a.setState(0);
          a.setUniqueID(id);

          lAlarms.remove(id);
          lAlarms.add(newAlarm);          
        }

      public void replaceList(ArrayList<Alarm> newList) {
          lAlarms.clear();
           lAlarms.addAll(newList);       
        }

      public ArrayList<Alarm> getAlarms() {
            return lAlarms;
        }

      public Alarm lastAlarmId() {
            return lAlarms.get(lAlarms.size()-1);
        }
  }  

<强> MyBroadcastReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
    AlarmHolder objAlarmHolder = AlarmHolder.getInstance();

    @Override
    public void onReceive(Context context, Intent intent) {

            // with this key we can catch the alarm which we want
        int key = intent.getIntExtra("key",0);


        for (Alarm alarm : objAlarmHolder.getAlarms()) {
            // if alarmstate is 1 and the key belogs that alarm device will vibrate
            if (alarm.getState() == 1 & alarm.getUniqueID() == key ) {
                Log.v("alarm", String.valueOf(String.valueOf(alarm.getUniqueID())));
                Toast.makeText(context, "your alarm id : " + String.valueOf(alarm.getUniqueID()),Toast.LENGTH_LONG).show();
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(2000);
            } else {
                Log.v("alarm", "canceled alarm number : " + String.valueOf(alarm.getUniqueID()));
            }

        }

    }

}

MainActivity.java

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText text;
    int uniqueInteger = 1;
    AlarmHolder objAlarmHolder = AlarmHolder.getInstance();
    ArrayList<Alarm> tempAlarmHolder = new ArrayList<Alarm>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.editText1);

        Button btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                            // we should pass unique integer to method 
                startAlert(uniqueInteger);
                uniqueInteger++;
            }
        });
    }

    public void startAlert(int rnd) {
        int i = Integer.parseInt(text.getText().toString());
        Bundle bundle = new Bundle();
        bundle.putInt("key", uniqueInteger);

        objAlarmHolder.registerAlarm(uniqueInteger);

        int alarmCount = 0;
        tempAlarmHolder.clear();


            // in this loop, all old alarms' state will set as 0
        for (Alarm alarm : objAlarmHolder.getAlarms()) {

            if(alarmCount < objAlarmHolder.getAlarms().size()-1)
            {
                Alarm objAlarm = new Alarm();
                objAlarm.setState(0);
                objAlarm.setUniqueID(alarmCount);               
                tempAlarmHolder.add(objAlarm);              
            }
            else
            {
                tempAlarmHolder.add(alarm);             
            }           
            alarmCount++;
        }

        objAlarmHolder.replaceList(tempAlarmHolder);




        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), getPendingIntent(bundle, uniqueInteger));
        Toast.makeText(this, "Alarm set in " + i + " seconds",
                Toast.LENGTH_LONG).show();
    }

    private PendingIntent getPendingIntent(Bundle bundle, int rc) {
        Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);

            // send alarm id to broatcast
        intent.putExtras(bundle);
        return PendingIntent.getBroadcast(this, rc, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
}

<强>的Manifest.xml

 <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
   <uses-permission android:name="android.permission.VIBRATE" ></uses-permission>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyBroadcastReceiver" >
        </receiver>
    </application>

<强> activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:text="Button" />

</RelativeLayout>

答案 1 :(得分:1)

你可以:

  1. 使用PendingIntent保留对您注册的AlarmManager对象的引用,并在注册新警报时致电PendingIntent.cancel取消它。
  2. 在创建FLAG_CANCEL_CURRENT时使用标记PendingIntent
  3. 使用这两种方法时,旧的警报将在创建新警报时被删除..