AndroidのBroadcastReceiver - システムBroadcast
例:
ACTION_TIME_CHANGED - 時刻変更~
ACTION_BATTERY_CHANGED - バッテリ容量変更
ACTION_BOOT_COMPLETED - システム起動完了
など
詳細: 【Standard Broadcast Actions】 http://developer.android.com/intl/ja/reference/android/content/Intent.html
サンプルコード
① MyReceiver.java(システム起動を受信する)
package com.example.liguofeng.launchreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 任意のservice起動 Intent tIntent = new Intent(context, MyService.class); context.startService(tIntent); Toast.makeText(context, "システム起動しました。", Toast.LENGTH_LONG).show(); } }
② MyReceiver2.java(低バッテリを受信する)
package com.example.liguofeng.launchreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver2 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "バッテリがすくねーよ", Toast.LENGTH_LONG).show(); } }
③AndroidManifest.xml(actionと権限設定)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.liguofeng.launchreceiver" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <receiver android:name=".MyReceiver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <receiver android:name=".MyReceiver2" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.BATTERY_LOW" /> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> </manifest>