gpt4 book ai didi

android - 开机后如何使用broadcastreceivers自动启动服务?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:09 27 4
gpt4 key购买 nike

<分区>

我使用的是 android 4.4 版本。开机后如何使用broadcastreceivers自动启动服务?提前致谢。更新: list 文件中的代码:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.prashanthi.trial.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".WordService"></service>
<receiver android:name=".MyScheduleReceiver" android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>

接收器类中的代码:

   public class MyScheduleReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
System.out.println("This is MyShedularReceiver");

Intent service = new Intent(context, WordService.class);
//service.setAction(RECEIVE_BOOT_COMPLETED);
context.startService(service);
}

}

服务类代码:

 public class WordService extends Service{
public void onCreate() {

super.onCreate();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (5 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in 5 seconds",
Toast.LENGTH_LONG).show();
}


@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

}

在主要 Activity 中,我有显示通知的代码。但问题是,在模拟器中运行应用程序后接收器类本身没有被触发....你能告诉我哪里出错了吗?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com