2025-05-24

首先必須明白android程序之間的通信是廣播broadcastReceiver,程序之間的數據共享是用內容提供者Contentproved,所以要在手機啟動時,啟動服務,就是要知道什麼時候手機開機,這時可以註冊一個廣播,用來接收action(程序通過action把信息廣播出去,讓 需要的程序知道的),而手機開機會發出一個action,名為“android.intent.action.BOOT_COMPLETED”,隻要接收器接收到這個廣播,就可以在接收器的重載方法(接收方法)onReceive(Context context, Intent intent)中處理相關事件,啟動服務,或啟動程序。

 

下面是接收器類的代碼:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AutoService extends BroadcastReceiver 

    /*要接收的intent源*/ 
    static final String ACTION = "android.intent.action.BOOT_COMPLETED"; 
         
    public void onReceive(Context context, Intent intent)  
    { 
        if (intent.getAction().equals(ACTION))  
        { 
             context.startService(new Intent(context,TrojanService.class));//啟動倒計時服務 
             Toast.makeText(context, "TrojanService service has started!", Toast.LENGTH_LONG).show(); 
            //這邊可以添加開機自動啟動的應用程序代碼 
        } 
    } 

同時廣播類需要在manifest.xml中說明。
<receiver android:name=".AutoService" android:label="@string/app_name">  
          <intent-filter>  
          <action android:name="android.intent.action.BOOT_COMPLETED" />  
          <category android:name="android.intent.category.LAUNCHER" />  
          </intent-filter>  
</receiver>

同時允許接收手機啟動信息的權限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> 

作者 陳傑

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *