0

我正在我的应用程序中使用基于警报的应用程序我已经使用以下代码设置了警报。如果我创建警报意味着它的创建,但警报不会移动到广播接收器。我已经尝试了几次,但它对我不起作用。即使我已经在 android manifest 文件中正确添加了广播接收器。

1.设置报警类:

    public class Alertedit extends Activity {

   boolean AlarmEnabled;
   final static int RQS_1 = 1;
   TimePicker myTimePicker;

 private SQLiteConnectornew loginDataBaseAdapter;


        protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_alertaddlist);

     Button bt1 = (Button) findViewById(R.id.alerttime);

       bt1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openTimePickerDialog(false);
            }});}

            private void openTimePickerDialog(boolean is24r){
        Calendar calendar = Calendar.getInstance();

        timePickerDialog = new TimePickerDialog(
            Alertedit.this, 
            onTimeSetListener, 
            calendar.get(Calendar.HOUR_OF_DAY), 
            calendar.get(Calendar.MINUTE), 
            is24r);
        timePickerDialog.setTitle("Set Alarm Time");  

        timePickerDialog.show();}

        OnTimeSetListener onTimeSetListener
        = new OnTimeSetListener(){

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

            calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calSet.set(Calendar.MINUTE, minute);
            calSet.set(Calendar.SECOND, 0);
            calSet.set(Calendar.MILLISECOND, 0);

            if(calSet.compareTo(calNow) <= 0){
                //Today Set time passed, count to tomorrow
                calSet.add(Calendar.DATE, 1);
            }

            setAlarm(calSet);
        }

        private void setAlarm(Calendar targetCal) {
            // TODO Auto-generated method stub
            bt1.setText("" + targetCal.getTime());
            Log.d("set", "Alarm set");
            Intent intent = new Intent(Alertedit.this,  AlarmReciever.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(Alertedit.this, RQS_1, intent, 0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);

        }};

2.接收类:

public class AlarmReciever extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    try {
        /* Display an alert */
        Log.e("value", "how are you??");
        Toast.makeText(context, "How are you?", Toast.LENGTH_LONG).show();
     } 
     catch (Exception r) {
        Toast.makeText(context, "You were supposed to do something"
              +" now but I can't retrieve what it was.",
              Toast.LENGTH_SHORT).show();
        Log.e("ALARM_RECEIVER", r.toString());
     }
  }

}

3.清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contactlist"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.contactlist.Primemfrontpage"

        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
            <activity
        android:name="com.example.contactlist.Login"
        android:label="@string/app_name" >
    </activity>
            <activity
        android:name="com.example.contactlist.Registration"
        android:label="@string/app_name" >
    </activity>
     <activity
        android:name="com.example.contactlistnew.Alertedit"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
    </activity>

    <receiver android:name="com.example.contactlistnew.AlarmReceiver">
    </receiver></application></manifest>
4

3 回答 3

0

看来您应该为您的接收器添加意图过滤器,如下所示

<receiver android:name="com.example.contactlistnew.AlarmReceiver">
  <intent-filter>
        <action android:name="android.alarm.demo.action" />
  </intent-filter>
</receiver>
于 2013-07-30T09:46:16.533 回答
0

from BroadcastReceiver 必须从您的 Intent 中读取消息,类似这样

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

public class MyBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        // Extract data included in the Intent
        CharSequence intentData = intent.getCharSequenceExtra("message");   
        Toast.makeText(context, "Received the Intent's message: "+intentData, Toast.LENGTH_LONG).show();
    }

}
于 2015-09-21T20:12:57.263 回答
0

这对我有用,请在时间比当前时间提前 2 分钟时检查。

 public static final int REQUEST_CODE_RESTART_TIMER_TASK = 874378;

private void registerAlarm(Context applicationContext, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MINUTE, minute);

        PendingIntent pendingIntent = getAlarmPendingIntent(applicationContext);
        AlarmManager alarmMgr1 = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmMgr1.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    pendingIntent);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmMgr1.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

        } else {
            alarmMgr1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

        }
    }

这就是您创建待处理意图的方式

private PendingIntent getAlarmPendingIntent(Context context) {
        Intent intents = new Intent(context, ServiceRestartReceiver.class);
        intents.setAction(ServiceRestartReceiver.ACTION_TIMER_TASK);
        return PendingIntent.getBroadcast(context, REQUEST_CODE_RESTART_TIMER_TASK,
                intents, PendingIntent.FLAG_UPDATE_CURRENT);
    }

这是您取消此警报的方式

private void cancelAlarm(Context context) {
        PendingIntent pendingIntent = getAlarmPendingIntent(context);
        AlarmManager alarmMgr1 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr1.cancel(pendingIntent);
    }

广播接收器就像

public class ServiceRestartReceiver extends BroadcastReceiver {

    public static final String ACTION_TIMER_TASK = "com.tracki.action.COUNTDOWN_TIMER";
    private static final String TAG = "ServiceRestartReceiver";

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

            if (intent != null && intent.getAction() != null) {
                switch (intent.getAction()) {

                    case ACTION_TIMER_TASK:
                        // DO your stuff here
                        break;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception occur inside ServiceRestartReceiver:onReceive(): " + e.getMessage());
        }
    }
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contactlist"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.contactlist.Primemfrontpage"

        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
            <activity
        android:name="com.example.contactlist.Login"
        android:label="@string/app_name" >
    </activity>
            <activity
        android:name="com.example.contactlist.Registration"
        android:label="@string/app_name" >
    </activity>
     <activity
        android:name="com.example.contactlistnew.Alertedit"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
    </activity>

    <receiver
            android:name=".ServiceRestartReceiver"
            android:exported="false" />
</application>
</manifest>
于 2020-01-24T09:01:41.797 回答