天天看點

Servie之前台Service

public class MyService extends Service {

    public static final String TAG = "MyService";

    private MyBinder mBinder = new MyBinder();

    @Override

    public void onCreate() {

        super.onCreate();

        Notification notification = new Notification(R.drawable.ic_launcher,

                "有通知到來", System.currentTimeMillis());

        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,

                notificationIntent, 0);

        notification.setLatestEventInfo(this, "這是通知的标題", "這是通知的内容",

                pendingIntent);

        startForeground(1, notification);

        Log.d(TAG, "onCreate() executed");

    }

    .........

}

我們首先建立了一個Notification對象,然後調用了它的setLatestEventInfo()方法來為通知初始化布局和資料,并在這裡設定 了點選通知後就打開MainActivity。然後調用startForeground()方法就可以讓MyService變成一個前台Service, 并會将通知的圖檔顯示出來。

繼續閱讀