在应用未打开时显示推送通知

时间:2015-12-02 05:18:26

标签: android android-intent android-activity notifications

我正在尝试为我的应用创建通知在某个任务到期时发送通知。每个任务都有截止日期,所以我想在截止日期过后为每个任务发送通知。

我的主要课程名为RecyclerViewDemoActivity,在onCreate()内我有:

public void setNotification()
{
    Intent intent=new Intent(this,NotificationClass.class);
    AlarmManager manager=(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
    PendingIntent pendingIntent= PendingIntent.getService(this, 0, intent, 0);
    // hardcoding the time just for this example
    manager.set(AlarmManager.RTC_WAKEUP,1449208683000,pendingIntent); 
}

我的NotificationClass看起来像这样:

public class NotificationClass extends Service {

    @Override
    public void onCreate()
    {
        Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
        PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
        Notification nBuilder= new Notification.Builder(this)
            .setContentTitle("This task is due!")
            .setContentIntent(pIntent)
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(1,nBuilder);

    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grokkingandroid.samplesapp.samples.recyclerviewdemo" >
<uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<application

    android:name="com.teamvallartas.autodue.RecyclerViewDemoApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="com.teamv.RecyclerViewDemoActivity"
        android:label="@string/app_name"
        android:configChanges="orientation"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

我查看了上面代码的this资源以及有关通知的Vogella's resource,但我不知道为什么这不起作用。

2 个答案:

答案 0 :(得分:1)

检查onCreate类的Service是否被调用。如果是,则问题是&#34; 您将代码置于错误的方法。&#34;。

您需要将代码移至onStartCommand(Intent intent, int flags, int startId)

喜欢

@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Intent resultIntent=new Intent(this, RecyclerViewDemoActivity.class);
        PendingIntent pIntent=PendingIntent.getActivity(this,0,resultIntent,0);
        Notification nBuilder= new Notification.Builder(this)
            .setContentTitle("This task is due!")
            .setContentIntent(pIntent)
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(1,nBuilder);

      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

更新您的清单并将此条目添加到其中

<service android:name=".NotificationClass" />

答案 1 :(得分:1)

你可以这样做,

第一个&gt; 创建一个本地广播接收器,

  • onReceive()方法中,将您的代码内容用于生成通知 ,这是 setNotification()方法。

第二个&gt; 您只需在 onCreate()中注册该广播接收器,然后在 onPause() onDestory中取消注册( )方法。像这样...

<强> ReceiverActivity.java

 public void onCreate(Bundle savedInstanceState) {    
  ...    
  // Register your broadcast receiver here ...      
  // with actions named "custom-event-name"...
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

protected void onDestroy() {
  // Unregister your receiver
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}
//here comes our receiver ...
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {

 //called setNotification() here ...
  }
};

现在假设您想要生成关于按钮点击事件的通知,然后像这样触发意图,

  Intent intent = new Intent("custom-event-name");
  // You can also include some extra data.
  intent.putExtra("message", "Its me!!!!");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 

你的** setNotification()**应该是这样的..

public void Notification(Context context, String message) {
        // Set Notification Title
        String strtitle = context.getString(R.string.notificationtitle);
        // Open NotificationView Class on Notification Click
        Intent intent = new Intent(context, NotificationView.class);
        // Send data to NotificationView Class
        intent.putExtra("title", strtitle);
        intent.putExtra("text", message);
        // Open NotificationView.java Activity
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // Create Notification using NotificationCompat.Builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context)
                // Set Icon
                .setSmallIcon(R.drawable.logosmall)
                // Set Ticker Message
                .setTicker(message)
                // Set Title
                .setContentTitle(context.getString(R.string.notificationtitle))
                // Set Text
                .setContentText(message)
                // Add an Action Button below Notification
                .addAction(R.drawable.ic_launcher, "Action Button", pIntent)
                // Set PendingIntent into Notification
                .setContentIntent(pIntent)
                // Dismiss Notification
                .setAutoCancel(true);

        // Create Notification Manager
        NotificationManager notificationmanager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        // Build Notification with Notification Manager
        notificationmanager.notify(0, builder.build());

    }