前台服務(在通知欄顯示服務)


關鍵代碼:

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

    @Override
    public void onCreate() {

        Intent notifyIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notifyIntent,0);

        Notification notification = new Notification.Builder(this).
                setSmallIcon(R.mipmap.ic_launcher).
                setContentTitle("通知").
                setContentText("我是服務的通知").
                setContentIntent(pendingIntent).
                setDefaults(Notification.DEFAULT_ALL). // 設置用手機默認的震動或聲音來提示
                build();

        // 設置為前台服務,在系統狀態欄顯示
        startForeground(1, notification);

        super.onCreate();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM