2014-11-06 2 views
4

У меня есть служба, работающая, и вы хотите отправить уведомление. Слишком плохо, для объекта уведомления требуется контекст, например Activity, а не служба.как показать оповещение и значок приложения Android

Знаете ли вы какой-либо способ, чтобы передать это? Я попытался создать Activity для каждого уведомления, это кажется уродливым, и я не могу найти способ запуска Activity без какого-либо представления.

я также хочу, чтобы послал мой значок приложения уведомления, чтобы показать значок верхней части экрана

+0

Используйте 'getApplicationContext()'. –

+0

Даже сервисы имеют контексты. Если вы не хотите использовать 'getApplicationContext()', вы можете использовать 'this' – Achrome

+0

ok, теперь как я могу отправить уведомление и значок приложения? –

ответ

0

Вот рабочий код, который создает уведомление от самой службы. надеюсь, что это вам поможет,

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.os.IBinder; 
import android.widget.Toast; 

public class MyService extends Service { 
    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 




    //We get a reference to the NotificationManager 
     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     String MyText = "Reminder"; 
     Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis()); 
     //The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears 

     String MyNotificationTitle = "Medicine!"; 
     String MyNotificationText = "Don't forget to take your medicine!"; 

     Intent MyIntent = new Intent(Intent.ACTION_VIEW); 
     PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
     //A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent 

     mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent); 

     int NOTIFICATION_ID = 1; 
     notificationManager.notify(NOTIFICATION_ID , mNotification); 
     //We are passing the notification to the NotificationManager with a unique id. 

     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
     return START_STICKY; 
    } 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
    } 
}