2014-02-19 6 views
3

Довольно новый в Android здесь :)Уведомления Builder в Android 2.3

У меня есть строитель уведомление, которое работает без проблем, если целевое приложение версия> 4,0 Однако при переходе на 2.3 я получаю ошибку на этой которая говорит: «Notificaiton.Builder не может быть разрешен к типу».

Notification notification = new Notification.Builder(this) 
      .setSmallIcon(drawable_small) 
      .setLargeIcon(drawable_big) 
      .setWhen(System.currentTimeMillis()).setTicker(content_title) 
      .setContentTitle(content_title).setContentInfo(content_info) 
      .setContentText(content_text).setContentIntent(pIntent) 
      .getNotification(); 

Эта проблема решена! Однако у меня есть еще один Это дает мне ошибку на каждом R (ресурсе), и у меня есть возможность импортировать R. Если я импортирую его, он дает мне ошибки на каждом ресурсе.

setContentView(R.layout.activity_main); 
+0

добавить 'поддержку библиотеки v4' в ваш LIBS –

+0

Notification.Builder пришел после того, как 2,3 поэтому вы не можете использовать таким образом. Я размещаю код, который будет работать в версии 2.3 – rahultheOne

ответ

9

Реализуйте Notification как

 Notification noti = new NotificationCompat.Builder(context) 
        .setSmallIcon(icon_small) 
        .setTicker(message) 
        .setLargeIcon(largeIcon) 
        .setWhen(System.currentTimeMillis()) 
        .setContentTitle(title) 
        .setContentText(message) 
        .setContentIntent(contentIntent) 
        //At most three action buttons can be added 
        .setAutoCancel(true).build(); 

И добавить библиотека поддержки v4 в проект, а также импортировать

import android.support.v4.app.NotificationCompat; 

NotificationCompat помощник для доступа к функции в Notification введенные после API level 4 в обратная совместимость ble мода.

Для получения дополнительной информации перейдите по ссылке: http://developer.android.com/guide/topics/ui/notifiers/notifications.html

1
  1. Добавить библиотеку поддержки v4 для вашего проекта, щелкнув правой кнопкой мыши проект, затем выбрать Android Tools> Добавить библиотеку поддержки

  2. Изменения в NotificationCompat.Builder

1
 NotificationManager notificationManager = 
      (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification n = new Notification(R.drawable.ic_launcher, 
    "New Message", 
    System.currentTimeMillis()); 
    Context context = getApplicationContext(); 
    String notificationTitle = "Got new Message"; 
    String notificationText = ""; 
    Intent myIntent = new Intent(MainActivity.this,MainActivity.class); 
    PendingIntent pendingIntent 
    = PendingIntent.getActivity(MainActivity.this, 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK); 
    n.defaults |= Notification.DEFAULT_SOUND; 
    n.flags |= Notification.FLAG_AUTO_CANCEL; 
    n.setLatestEventInfo(context, 
     notificationTitle, 
     notificationText, 
     pendingIntent); 
    notificationManager.notify(1,n); 
+3

. Вы просто скопировали некоторый случайный код, который не отвечает на вопрос. –

4

Попробуйте это:

int currentapiVersion = android.os.Build.VERSION.SDK_INT; 
Notification notification; 

// To support 2.3 os, we use "Notification" class and 3.0+ os will use 
// "NotificationCompat.Builder" class. 
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { 
notification = new Notification(icon, message, 0); 
notification.setLatestEventInfo(context, appname, message, 
contentIntent); 
notification.flags = Notification.FLAG_AUTO_CANCEL; 
notificationManager.notify(0, notification); 

} else { 
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context); 
notification = builder.setContentIntent(contentIntent) 
.setSmallIcon(icon).setTicker(appname).setWhen(0) 
.setAutoCancel(true).setContentTitle(appname) 
.setContentText(message).build(); 

notificationManager.notify(0 , notification); 
} 

Надеюсь, это поможет.

0

Надеется, что это работает :)

NotificationCompat.Builder mBuilder = 
     new NotificationCompat.Builder(context) 
     .setSmallIcon(R.drawable.ic_launcher) 
     .setContentTitle("My notification") 
     .setContentText("Hello World!"); 
// Creates an explicit intent for an Activity in your app 
Intent resultIntent = new Intent(getApplicationContext(), MYDEMOACTIVITY.class); 

// The stack builder object will contain an artificial back stack for the 
// started Activity. 
// This ensures that navigating backward from the Activity leads out of 
// your application to the Home screen. 
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 
// Adds the back stack for the Intent (but not the Intent itself) 
stackBuilder.addParentStack(MYDEMOACTIVITY.class); 
// Adds the Intent that starts the Activity to the top of the stack 
stackBuilder.addNextIntent(resultIntent); 
PendingIntent resultPendingIntent = 
     stackBuilder.getPendingIntent(
      0, 
      PendingIntent.FLAG_UPDATE_CURRENT 
     ); 
mBuilder.setContentIntent(resultPendingIntent); 
NotificationManager mNotificationManager = 
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

// mId allows you to update the notification later on. 
mNotificationManager.notify(mId, mBuilder.build()); 

И добавить поддержку библиотеки v4 в свой проект, а также импортировать

import android.support.v4.app.NotificationCompat;