安卓应用程序带有每日通知

9
我正在开发一个安卓应用程序,我一直在尝试编写代码来设置每天特定时间的通知。起初,我认为这将是一项容易的任务,几乎所有在Play商店中的应用都有计时通知。但是,在反复搜索之后,我找到的所有方法和Youtube教程都无法为我工作。问题可能出在我身上,但我不知道具体原因。我只需要一个简单、优雅、易于理解的方法(如果有的话)。非常感谢您的帮助。
我所做的所有搜索都让我走了这么远......但仍然没有任何运气:
这个方法在我的MainActivity类中,只有在首次启动应用程序时才会被调用以设置闹钟...
private void alarmMethod() {
    Intent myIntent = new Intent(this, NotifyService.class);
    AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
    pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

    // Set the alarm to start at approximately 2:00 p.m.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 14);

    // With setInexactRepeating(), you have to use one of the AlarmManager interval
    // constants--in this case, AlarmManager.INTERVAL_DAY.
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent);

    Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG)
            .show();

以下是我的 NotifyService 类:

package com.OHS.example;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

public class NotifyService extends Service {

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

@Override
public void onCreate() {
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification mNotify = new NotificationCompat.Builder(this)
        .setContentTitle("Title")
        .setContentText("Hello World!")
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentIntent(pIntent)
        .setSound(sound)
        .build();

    mNM.notify(1, mNotify);

}
}
3个回答

5

试试这段代码。 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/TextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Android Alarm Example:\n\rSetup an alarm event after 10 seconds from the current time. So just press Setup Alarm button and wait for 10 seconds. You can see a toast message when your alarm time will be reach." />

    <Button
        android:id="@+id/setAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:onClick="onClickSetAlarm"
        android:text="Set Alarm" />

主要活动:

public class MainActivity extends Activity {

    //used for register alarm manager
    PendingIntent pendingIntent;
    //used to store running alarmmanager instance
    AlarmManager alarmManager;
    //Callback function for Alarmmanager event
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Register AlarmManager Broadcast receive.
        RegisterAlarmBroadcast();
    }
    public void onClickSetAlarm(View v)
    {
        //Get the current time and set alarm after 10 seconds from current time
        // so here we get 
        alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000 , pendingIntent );
    }
    private void RegisterAlarmBroadcast()
    {
          Log.i("Alarm Example:RegisterAlarmBroadcast()", "Going to register Intent.RegisterAlramBroadcast");

        //This is the call back function(BroadcastReceiver) which will be call when your 
        //alarm time will reached.
        mReceiver = new BroadcastReceiver()
        {
            private static final String TAG = "Alarm Example Receiver";
            @Override
            public void onReceive(Context context, Intent intent)
            {
                Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
            }
        };

        // register the alarm broadcast here
        registerReceiver(mReceiver, new IntentFilter("com.myalarm.alarmexample") );
        pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.myalarm.alarmexample"),0 );
        alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    }
    private void UnregisterAlarmBroadcast()
    {
        alarmManager.cancel(pendingIntent); 
        getBaseContext().unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }
}

我希望这能对你有所帮助,这对我很有效。 你可以计算并设置想要触发警报的时间。 愉快的编码!

这真是太棒了...我无法形容我有多感激。一直以来,我一直在尝试启动另一个负责显示通知的活动,但这会引起问题。我从未想过可以让同一个类拥有alarmManager和显示通知。你的解决方案非常优雅且非常有帮助。谢谢。 - OHS
我确实有一个问题....在设置了闹钟之后,如果我完全退出应用程序(从多任务窗口),闹钟不会响起,我也不会收到通知。我甚至尝试删除onDestroy()方法,但这并没有帮助。有什么想法可以让闹钟响起,即使应用程序当前没有启动? - OHS
尽管我理解了您上述的问题,但请勿删除onDestroy()方法,只需将unregisterReceiver()方法注释掉即可。这样就可以完成了。 - Trideep
仍然没有任何反应...一切都正常工作,警报每10秒钟响一次,直到我从多任务窗口退出应用程序,之后就没有通知了。我认为alarmManager的整个意义在于在特定时间在后台执行某些操作。 - OHS
请检查您是否在任何地方调用了UnregisterAlarmBroadcast(),因为它不应该以那种方式运行。 - Trideep
显示剩余2条评论

2
你可以使用AlarmManager来安排每日通知。这里的文档提供了很好的解释和示例。
设置闹钟。
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
    new Intent(this, MainService.class),
        PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar calendar = Calendar.getInstance();
    // set the triggered time to currentHour:08:00 for testing
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 8);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), 0, pendingIntent);

处理报警的服务。

public class MainService extends IntentService {

    public MainService() {
        super("mainservice");
    }

    public MainService(String name) {
        super(name);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.IntentService#onHandleIntent(android.content.Intent)
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        showNotification();
    }

    private void showNotification() {

        Uri soundUri = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("Alarm title")
                .setContentText("Alarm text")
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, new Intent(this,
                                SecondActivity.class),
                                PendingIntent.FLAG_UPDATE_CURRENT))
                .setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
                .build();
        NotificationManagerCompat.from(this).notify(0, notification);
    }

}

非常感谢...但我已经尝试过了...我应该在发布问题时附上代码。抱歉,我有点新手。我稍后会去编辑它。 - OHS
正如您所看到的... 我从您发送给我的同一份文档中获取了代码的第一部分... 而第二部分则来自不同的教程,我尝试在按下按钮时显示通知... 它可以工作,因此问题不应该出现在第二部分。第一部分有什么问题吗? - OHS
@OHS,你的第一部分看起来没问题。但是第二部分似乎不太对。你不应该在回调函数onCreate中发送通知,因为它只会在服务首次创建时调用一次。我猜想,你没有看到通知是因为你的服务已经创建了,onCreate不会再次调用。 - alijandro
好的……我试了一下,除了最后的NotificationManagerCompat外,一切似乎都正常…它给了我一个错误:“NotificationManagerCompat无法解析”……根据我在互联网上找到的资料,我必须去Android SDK管理器并从那里更新…所以我这样做了,但仍然没有任何进展。你有什么主意? - OHS
@OHS,你可以直接使用NotificationManager来查看它是否有效。 - alijandro
很不幸...我尝试了使用“NotificationManager”来查看它是否有效,但它没有...然后我费了很大的劲才让“NotificationManagerCompat”起作用,只是意识到这不是问题所在...我的代码与你的完全一样,没有改变任何东西。但仍然没有通知,我什么也没有得到。 - OHS

0

正如alijandro所说,如果您想在特定时间每天收到通知,可以使用AlarmManager进行安排,在该时间显示通知;或者如果您想从服务器获取数据,请发送HTTP请求以检索您的数据并向用户显示通知。 但是,如果您想随时获得推送通知,可以使用GCM(Google云消息传递)。请查看此doc


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接