【问题标题】:Displaying push notification while app is not open应用未打开时显示推送通知
【发布时间】:2015-12-02 05:18:25
【问题描述】:

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

我的主类叫做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,但我不知道为什么这不起作用。

【问题讨论】:

  • 您是否分析了日志...是否调用了 onCreate of Service?如果没有,请检查您的服务是否已添加到清单中。
  • @PankajKumar 你是对的......它似乎没有调用它。
  • 然后检查清单。您需要在那里添加服务。
  • @PankajKumar 我猜想添加一个活动?但这不需要一个 XML 文件吗?

标签: android android-intent android-activity notifications


【解决方案1】:

检查onCreateService 类是否被调用。如果是,那么问题是“您将代码放置在错误的方法中。”。

您需要将代码移动到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" />

【讨论】:

  • 所以我将代码移动到 onStartCommand 并尝试打印一些东西,但它没有出现在日志中......我错过了什么?
  • 完成。它与意图标签有关吗?顺便说一句,我删除了其他不相关文件的其他活动。
  • '' 将此条目添加到清单中,在活动标记下方。
  • 哦...空间解决了它...但它仍然不打印 onStartCommand() 中的语句...这不应该发生对吗?
  • 好吧,我不知道 onStartCommand() 是否应该打印任何打印语句,因为它不是,但我确实收到了通知。我需要在 NotificationClass 的 onCreate 中做任何事情吗?
【解决方案2】:

你可以这样做,

1st >创建一个本地广播接收器,

  • onReceive() 方法中,放置您的代码内容以生成通知 ,那是你的 setNotification() 方法。

2nd > 您只需在 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());

    }

【讨论】:

  • 看起来很复杂,我在gist.github.com/Antarix/8131277 看到了类似的教程,但我想我现在坚持使用更简单的方法。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多