0

我正在尝试使用警报管理器定期在活动中启动代码。我在这里查看了各种示例,但它们并没有真正帮助。

出于测试目的,我所要做的就是每隔 10 秒弹出一个 toast,但似乎什么都没有发生。请帮助伙计们!

我在清单中有这个(也是所有三个活动的声明):

<receiver android:name=".receiver.AlarmReceiver"></receiver> 

OnCreate 中主要活动的代码:

        //
        // Setting up the Alarm Manager
        //
        Intent myIntent = new Intent(getBaseContext(), AlarmReceiver.class); 
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0,         myIntent, 0); 
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
        Calendar calendar = Calendar.getInstance(); 
        calendar.setTimeInMillis(System.currentTimeMillis()); 
        calendar.add(Calendar.SECOND, 10); 
        long timerInterval = 10 * 1000;  
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timerInterval, pendingIntent); 
        //finish();  

警报接收器.java:

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

public class AlarmReceiver extends BroadcastReceiver 
{

public void onReceive(Context context, Intent intent) 
    { 
    Toast.makeText(context," onRecieve() test" , Toast.LENGTH_LONG).show(); 
    Intent scheduledIntent = new Intent(context, MyService.class); 
    scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    context.startActivity(scheduledIntent);
    } 
}

我的服务.java:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {


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


 Toast.makeText(getBaseContext(),"test message.",
            Toast.LENGTH_SHORT).show();

}
@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

}

4

2 回答 2

0

您的活动未显示,因为您正在调用标识startActivity()的。您应该在 LogCat 中看到与此相关的警告。IntentService

我谦虚地建议您通过Log类自己使用 LogCat 来记录后台操作,而不是尝试使用Toast.

于 2012-08-27T17:28:25.453 回答
0

测试这段代码:

private void establecerAlarmaClick(int when){
AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivityAlarmita.this, MainActivityAlarmita.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivityAlarmita.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + when * 1000, pendingIntent);
}
于 2016-03-18T16:01:19.653 回答