ตัวอย่างโปรแกรมไฟกระพริบ บน Android

ลองอ่านเว็บนอก เค้าบอกว่า LED ของ Android จะทำงานก็ต่อเมื่อหน้าจอดับเท่านั้น ตัวอย่างนี้ เป็นการสั่ง LED ให้กระพริบเมื่อหน้าจอดับและสามารถทดสอบ LED ของเราด้วยว่ารองรับสีอะไรบ้าง โดยมีขั้นตอนทำงานประมาณนี้

  1. กดปุ่ม button1 เพื่อ start service ให้สั่ง receiver ทำงานเมื่อเปิด/ปิดหน้าจอ
  2. กดปุ่ม button2 เพื่อ stop service ด้านบน
  3. spinner ไว้เลือกสีทดสอบ
  4. เมื่อ กด button 1 แล้ว จะพบว่ามีไฟกระพริบตามสีที่เลือก(แล้วแต่เครื่องจะรองรับสีไรได้บ้าง) เมื่อกดเปิดหน้าจอไฟกระพริบจะเลิกทำงาน
ตัวอย่างหน้าจอตัวอย่าง Sourcecode

NotiRcv.java

package com.duckprog.example;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class NotiRcv extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("======"+intent.getAction());
		//ทำงานเมื่อหน้าจอดับ
		if (intent.getAction()
				.equalsIgnoreCase(Intent.ACTION_SCREEN_OFF)) {
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification noty = new Notification(R.drawable.ic_launcher,
				"", System.currentTimeMillis());
			noty.ledARGB = TestLEDColorsActivity.loadColorPref(context);
			noty.ledOnMS = 500;
			noty.ledOffMS = 1000;
			noty.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
			PendingIntent contentIntent = PendingIntent.getActivity(
					context, 0, intent, 0);
			noty.setLatestEventInfo(context, "", "", contentIntent);

			notificationManager.notify(1, noty);
				System.out.println("=========");
		}
		//ยกเลิก Notification เมื่อเปิดหน้าจอ
		else	if (intent.getAction()
				.equalsIgnoreCase(Intent.ACTION_SCREEN_ON)) {
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.cancel(1);
		}
	}

}

ดาวน์โหลด  source code ทั้งหมด