如何在启动时调用BroadcastReceiver? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

请求任何人帮助我,我是android开发的新手。我想在启动时调用broadcastreciver。但它不工作。我的源代码

我得到了清单的许可

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tajmirkhan.broadcasetreciver_new">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".Bootservice" android:exported="true" android:enabled="true">
            <intent-filter android:priority="500">
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>

        </receiver>
    </application>

</manifest>

这个是我的广播接收者课程

public class Bootservice extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("dd","above the onReceive mthode");
        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            Toast.makeText(context, "boot completed ", Toast.LENGTH_SHORT).show();
            Log.e("dd","inisde the onReceive mthode");
        }
    }
}

这是我的主要活动

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("dd","oncreat ");

    }
}
javascript android
2个回答
0
投票

你忘了给<category android:name="android.intent.category.HOME"/>打电话,只需在你的接收器上添加一行

<receiver 
      android:name=".Bootservice" android:exported="true" android:enabled="true">
      <intent-filter android:priority="500">
      <category android:name="android.intent.category.HOME"/>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>
      </intent-filter>

   </receiver>

这一行:

<category android:name="android.intent.category.HOME"/>

表示当您按下主页按钮时,您的应用程序将被列为启动启动器主页或您的主页活动的选项(以及在其活动清单中具有此类别的所有应用程序)。更简单的是,每当您按下主页按钮时,将列出手机中安装的所有应用程序,其中包含CATEGORY.HOME类别和在其AndroidManifest.xml中的intent-filter中的Action_Main(除非您选择了某些应用程序作为默认应用程序)一个选择器,供用户选择他们想要启动的HOME。

快乐的编码!!


0
投票

不知道这是否是修复但尝试修改:

if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))

至:

if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED))
© www.soinside.com 2019 - 2024. All rights reserved.