代码之家  ›  专栏  ›  技术社区  ›  michael

Android:警报未启动服务

  •  0
  • michael  · 技术社区  · 9 年前

    要求: 重复启动后台服务

    设计: 使用 AlarmManager

    我做了什么:

    <service
        android:name=".MyService"
        android:exported="false" >
    </service>
    
    AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, MyService.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), SERVICE_ALARM_INTERVAL, pendingIntent);
    

    服务级别是直接的 extends Service 具有:

    @Override
    public void onCreate() {              
        HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        //Get the HandlerThread's Looper and use it for our Handler
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
        mContext = getApplicationContext();
        Toast.makeText(mContext, "Service!!!!!", Toast.LENGTH_LONG).show();
        Log.e("tag", "Service!!!");
    }
    

    问题: 这个 Toast 消息和 Log 未执行打印。

    我在这里做错了什么?

    谢谢

    2 回复  |  直到 9 年前
        1
  •  2
  •   ianhanniballake    9 年前

    您正在使用 PendingIntent.getBroadcast() -这将触发广播。你需要使用 PendingIntent.getService() 如果你想触发一个服务。

        2
  •  1
  •   Ijas Ahamed N    9 年前

    试试这个

    Android清单.xml

    <receiver android:name=".AlarmReceiver">
       <intent-filter>
            <action android:name="com.example.project.AlarmReceiver" />
       </intent-filter>
    </receiver>
    

    主活动.java

    Intent intent = new Intent(context, AlarmReceiver.class);
    
    intent.setAction("com.example.project.AlarmReceiver");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), SERVICE_ALARM_INTERVAL, pendingIntent);
    

    AlarmReceiver.java

    public class AlarmReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Alarm received!!!!!", Toast.LENGTH_LONG).show();
        }
    
    }
    

    将使用如上所示的广播接收器调用AlarmManager