在android应用程序中创建文件,由广播接收器检查以执行操作

在android应用程序中创建文件,由广播接收器检查以执行操作,android,android-contentprovider,android-file,Android,Android Contentprovider,Android File,因此,目前我在android应用程序中有一个开关,打开它时会创建一个文件(关闭时会删除该文件)。当我打开电话时,广播接收到检查文件是否存在。如果有,那么它会运行一些安装程序。问题是我在数据目录(而不是应用程序的数据目录)中创建了应用程序。因此,权限存在问题,我必须使用su chmod来更改访问权限。我想避免这个问题,所以我考虑了ContentProviders 我是否应该选择内容提供商,或者如果我不需要读取文件,是否有更简单的方法,只需检查它是否存在 我可以在应用程序数据空间中创建文件并从广播接

因此,目前我在android应用程序中有一个开关,打开它时会创建一个文件(关闭时会删除该文件)。当我打开电话时,广播接收到检查文件是否存在。如果有,那么它会运行一些安装程序。问题是我在数据目录(而不是应用程序的数据目录)中创建了应用程序。因此,权限存在问题,我必须使用su chmod来更改访问权限。我想避免这个问题,所以我考虑了ContentProviders

我是否应该选择内容提供商,或者如果我不需要读取文件,是否有更简单的方法,只需检查它是否存在


我可以在应用程序数据空间中创建文件并从广播接收器访问它吗

尝试一个包含数据的广播接收器

发送:

Intent intent = new Intent("my.action.string");
intent.putExtra("on", true);
sendBroadcast(intent);
public void onReceive(Context context, Intent intent) {
  if(intent.getAction().equals("my.action.string")){
     boolean state = intent.getExtras().getBoolean("on");
  }
}
<receiver android:name=".MyReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="my.action.string" />
    </intent-filter>
</receiver>
接收:

Intent intent = new Intent("my.action.string");
intent.putExtra("on", true);
sendBroadcast(intent);
public void onReceive(Context context, Intent intent) {
  if(intent.getAction().equals("my.action.string")){
     boolean state = intent.getExtras().getBoolean("on");
  }
}
<receiver android:name=".MyReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="my.action.string" />
    </intent-filter>
</receiver>
清单:

Intent intent = new Intent("my.action.string");
intent.putExtra("on", true);
sendBroadcast(intent);
public void onReceive(Context context, Intent intent) {
  if(intent.getAction().equals("my.action.string")){
     boolean state = intent.getExtras().getBoolean("on");
  }
}
<receiver android:name=".MyReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="my.action.string" />
    </intent-filter>
</receiver>


为什么不使用SharedReferences?“您可以使用SharedReferences保存任何基本数据:布尔值、浮点值、整数、长度和字符串。这些数据将在用户会话中保持不变(即使您的应用程序被终止)。“如果手机关闭,它会保持不变吗?是,它存储在一个私人文件中。我没有尝试过,但我认为可能会出现的问题是,一旦我将开关切换到ON位置并关闭手机,当我重新打开时,检测文件并执行某些代码的广播接收器应用程序不会执行任何操作,因为它没有接收到意图。实际上,在活动之间交换这些信息的最佳方式似乎是我能够使用广播接收器与另一个应用程序通信,该应用程序随后创建并删除了文件。谢谢