如何使用服务显示通知?

时间:2014-01-02 10:31:45

标签: android service notifications broadcastreceiver

我试图使用后台服务显示通知,我写了3个类。该服务应该在后台运行,即使应用程序已关闭,它应该自动开始运行,所以我使用了

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.s2si.ucom.ui.UcomBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

因此,在BroadcastReceiver类的onReceive()中,我正在使用

启动服务
Intent service = new Intent(context, AlarmService.class);
    context.startService(service);

在服务类中,我使用AlarmManager来设置特定的间隔,以便我可以显示每个时间段的通知。最后我调用BroadcastReceiver类来使用AlarmManager显示通知。问题是我没有得到输出: - (而不是我得到的错误,无法加载memtrack模块(没有这样的文件或目录)...我对Android编码很新...任何人都可以帮助我如何以这种方式显示通知..让我知道我上面做错了什么...非常感谢: - )。

服务类的onCreate()方法中的代码,

    Intent intent = new Intent(context, NotificationServiceReceiver.class);

    PendingIntent sender = PendingIntent
            .getBroadcast(context, 0, intent, 0);

    // We want the alarm to go off 5 seconds from now.
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 5 * 1000;// start 5 seconds after first register.

    // Schedule the alarm!
    AlarmManager alarmManager = (AlarmManager) context
            .getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            firstTime, 5000, sender);// 5seconds interval

1 个答案:

答案 0 :(得分:1)

简而言之,就是你创建广播的方式

private static final String ACTION_ALARM = "your.company.here.ACTION_ALARM";

public static void createAlarm(){
  Intent alarmIntent = new Intent();
  alarmIntent.setAction(ACTION_ALARM);

   PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
   AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

   am.set(AlarmManager.RTC_WAKEUP, timestamp for alarm, pi);
}

public void onReceive(...){
   //whatever is supposed to happen on receive
}

你需要声明broadcastreceiver和它应该在manifest中接收的actionname:

<receiver
    android:name="your.company.here.AlarmReciever">
    <intent-filter>
        <action android:name="your.company.here.ACTION_ALARM" />
    </intent-filter>
</receiver>