如果该应用程序安装在外部存储设备上,我该如何使用广播接收器并为它们提供服务。我对其进行了编程,但仅在内部存储设备上运行,因为我希望在设备重新启动服务时运行,而不要启动活动

我的活动:

 public class FirstClass extends Activity
 {
  public void onCreate(Bundle savedInstanceState)
 {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first);
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable()
    {
       public void run()
       {
        startService(new Intent(getApplicationContext(), MyService.class));
        startActivity(new Intent(FirstClass.this, MainActivity.class));
        finish();
       }
    },5000);
  }
 /////////////////////////////////////////////////
 }


我的广播接收器:

 public class BroadcastReceiverOnTurnedOn extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
  Intent startServiceIntent = new Intent(context, MyService.class);
  context.startService(startServiceIntent);
   }
 }


我补充说:

<service
    android:name="com.dariran.MyService"
    android:enabled="true"
    android:exported="true" >
</service>
<receiver android:name="com.dariran.BroadcastReceiverOnTurnedOn"
android:enabled="true">
  <intent-filter android:priority="1">
    <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
  <intent-filter>
    <action  android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />
  </intent-filter>
</receiver>


到Manifest.xml上的appliation标签,并
我将此代码添加到我的服务类中,以放置一个过滤器以识别外部存储,但是不再起作用:(

 @Override
 public void onStart(Intent intent, int startId) {
 try {

 IntentFilter filter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
 BroadcastReceiver mReceiver = new BroadcastReceiverOnTurnedOn();
 registerReceiver(mReceiver, filter);

 } catch (Exception e) {
 }
}

最佳答案

引用the documentation


  为了使您的应用程序始终如一地正常运行,如果使用以下任何功能,则不应允许将应用程序安装在外部存储中...
  
  广播接收器正在监听“启动完成”
     在将外部存储器安装到设备上之前,系统会传递ACTION_BOOT_COMPLETED广播。如果您的应用程序安装在外部存储器上,则它将永远不会收到此广播。


the documentation, this time for ACTION_EXTERNAL_APPLICATIONS_AVAILABLE中的其他地方引用:


  额外数据EXTRA_CHANGED_UID_LIST包含其可用性已更改的软件包的uid列表。请注意,此列表中的软件包不接收此广播。


因此,您需要将您的应用设置为不安装在外部存储上。

07-24 09:44
查看更多