Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 簡易手機響鈴功能的實現

當有新通知抵達時,我們常以響鈴提醒使用者。本文示範如何透過幾行程式碼,播放系統預設的鈴聲,重點在於善用 Notification 與 NotificationManager。

關鍵代碼如下:

import java.util.Random;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.media.AudioManager;

public class TipHelper {

    // 播放默認鈴聲,返回 Notification id
    public static int PlaySound(final Context context) {
        NotificationManager mgr = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification nt = new Notification();
        nt.defaults = Notification.DEFAULT_SOUND;
        int soundId = new Random(System.currentTimeMillis())
                .nextInt(Integer.MAX_VALUE);
        mgr.notify(soundId, nt);
        return soundId;
    }
}

呼叫時,把 Activity 的參照傳進去即可。要留意的是,若手機處於靜音模式,這段程式自然是響不出聲音的。

Copyright © Linux教程網 All Rights Reserved