Cil*_*nco 17 notifications android broadcastreceiver
我尝试使用此代码创建通知:
private void setNotificationAlarm(Context context)
{
Intent intent = new Intent(getApplicationContext() , MyNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 , pendingIntent);
Log.d("ME", "Alarm started");
}
public class MyNotification extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("ME", "Notification started");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我的Mainfest宣言:
<receiver
android:name=".MyNotification"
android:enabled="true"
android:exported="false" >
</receiver>
Run Code Online (Sandbox Code Playgroud)
我现在的问题是,生成了警报,但未显示通知.BroadcastReceiver在mainfest文件中声明,没有编译器或运行时错误.
我的第二个问题是setLatestEventInfo和new NotificationContructor已被弃用.我可以用什么代替呢?
我想你需要用
PendingIntent.getBroadcast (Context context, int requestCode, Intent intent, int flags)
Run Code Online (Sandbox Code Playgroud)
代替 getService
您可以使用
Intent switchIntent = new Intent(BROADCAST_ACTION);
而不是使用
Intent intent = new Intent(getApplicationContext() , MyNotification.class);
在这里,BROADCAST_ACTION是您在清单中定义的操作
<receiver android:name=".MyNotification " android:enabled="true" >
<intent-filter>
<action android:name="your package.ANY_NAME" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
你可以通过使用该动作名称来捕获它
public class MyNotification extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String act = "your package.ANY_NAME";
if(intent.getAction().equals(act)){
//your code here
}
}}
Run Code Online (Sandbox Code Playgroud)