簡體   English   中英

我可以使用廣播接收器啟動另一個應用程序嗎?

[英]can i start another application using the broadcast receiver?

我只是想知道我已經創建了一個應用程序並將其安裝在我的設備上。是否可以僅使用廣播接收器來啟動此應用程序?

在應用程序未運行時,使用以下代碼打開活動。

Intent myIntent = new Intent(context.getApplicationContext(), YourClassActivity.class);
Bundle bundle = new Bundle();
myIntent.putExtras(bundle);
myIntent.addFlags(
      Intent.FLAG_ACTIVITY_NEW_TASK
    | Intent.FLAG_ACTIVITY_CLEAR_TOP
    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.getApplicationContext().startActivity(myIntent);

您可以在包內傳遞任何數據,例如

bundle.putString("title", "from receiver");

如果BroadcastReceiver正在偵聽,則應用程序也在“運行”。 如果您打算打開“活動”,那么

@Override
public void onReceive(Context context, Intent intent) {
    context.startActivity(new Intent(context, YourActivity.class));
}

您需要在清單中靜態注冊接收者(來自doc)

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml. 您還應該指定您無法捕捉的意圖動作

<receiver android:name=".YourReceiver"
    android:exported="true"
    android:enabled="true" >
    <intent-filter>
       <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

發送廣播時,您需要添加一個標志來啟動尚未運行的程序包。

getContext().sendBroadcast(new Intent("MY_ACTION").setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES), null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM