简体   繁体   中英

AlarmManager won't start service

I just followed the exact code in API Demo, but my service just won't start after I set the AlarmManager.

so my service is

public class CourseWatcherRefreshService extends Service {

    private CourseDbAdapter mDbHelper;
    private CourseWatcher watcher;

    @Override
    public void onCreate() {
        Toast.makeText(this, "Watcher Refresh Service starts", Toast.LENGTH_SHORT).show();
        mDbHelper = new CourseDbAdapter(this);
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        mDbHelper.open();
        Thread thread = new Thread(null, mTast, "CourseWatcherRefreshService");
        thread.start();
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        mDbHelper.close();
        super.onDestroy();

    }

    Runnable mTast = new Runnable() {
        // some work
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new Binder() {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };

}

Also in my AndroidManifest.xml, I put such code

<service
    android:name=".CourseWatcherRefreshService"
    android:process=":remote" >
</service>

And I use such code to toggle the AlarmManager

PendingIntent refreshIntent = PendingIntent.getActivity(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime, 30*1000, refreshIntent);

And the code above is almost the same with the AlartService example in API Demo, but my code won't work, I can't see any sign of my service starts to work.

You are using getActivity when you should be using getService . So change the PendingIntent line to

PendingIntent refreshIntent = PendingIntent.getService(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);

try this :

Intent updateIntent = new Intent() 
updateIntent.setClass(NaviScreen.this, CourseWatcherRefreshService.class) 
PendingIntent pendingIntent = PendingIntent.getService(this, 0, updateIntent, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM