BroadCastReceiver(廣播接收者)開機啓動完成監聽例子

 

一、在配置清單裏靜態註冊BroadCastReceiverandroid

 

 

代碼app

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiver.boot"
    android:versionCode="1"
    android:versionName="1.0" >ide

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <!-- 添加開機啓動完成的權限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
spa

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />xml

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<!-- 靜態註冊廣播接收者(實施監聽) -->
        <receiver
            android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>utf-8

 

 

 

 

=================get

 

 

 

二、BootReceiver類string

 

 

代碼it

 

 

public class BootReceiver extends BroadcastReceiver {io

 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub

  Toast.makeText(context, "監聽到開機完成", Toast.LENGTH_LONG).show();
  
  Intent intent1 = new Intent(context,MainActivity.class);
  //必需要添加這個標籤 不然啓動失敗
  intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  //跳轉
  context.startActivity(intent1);
 }

}

相關文章
相關標籤/搜索