Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

android - Send notification once in a week

I want to notify the user about answer the weekly questions.I need to send the notification to the user even my app is not running.The notification will send once in a week. When user clicks the notification my app will gets open. I tried this via Timer and TimerTask().This notifies the user when my app is running.How can I send the notification to the user while app is not running.

Anyone can help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code uses Alarmmanager with BroadcastReceiver which will help you out achieving your need.

In your activity:

Intent intent = new Intent(MainActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, System.currentTimeInMillis(), am.INTERVAL_DAY*7, pendingIntent);

System.currentTimeInMillis() - denotes that the alarm will trigger at current time, you can pass a constant time of a day in milliseconds.

Then create a Receiver class something like this,

public class Receiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        showNotification(context);
    }

    public void showNotification(Context context) {
        Intent intent = new Intent(context, AnotherActivity.class);
        PendingIntent pi = PendingIntent.getActivity(context, reqCode, intent, 0);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.android_icon)
            .setContentTitle("Title")
            .setContentText("Some text");
        mBuilder.setContentIntent(pi);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(reqCode, mBuilder.build());
    }
}

Also you have to register your BroadcastReceiver class in your manifest file, like the following. In your AndroidManifest.xml file, inside tag,

<receiver android:name="com.example.receivers.Receiver"></receiver>

Here "com.example.receivers.Receiver" is my package and my receiver name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...