我已經編寫了一個包含服務類和活動的應用程序。如何在後臺運行我的應用程序24X7,用於偵聽聯繫人數據庫中的更改
我從活動開始了服務這樣
public class RecycleBinActivity extends Activity {
/** Called when the activity is first created. */
Uri cpath=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cpath=ContactsContract.Contacts.CONTENT_URI;
this.getApplicationContext().getContentResolver().registerContentObserver(cpath, true, observer);
}
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Intent i=new Intent(RecycleBinActivity.this.getApplicationContext(),DeleteService.class);
startService(i);
}
@Override
public boolean deliverSelfNotifications()
{
super.deliverSelfNotifications();
return true;
}
}
MyContentObserver observer=new MyContentObserver();
}
和我的服務實現如下所示
public class DeleteService extends Service {
private final IBinder mBinder = new LocalBinder();
Notification nf;
NotificationManager nfm;
Uri cpath,lookupuri;
String lookupkey;
Cursor cur;
Runnable refresher;
ContentResolver cr;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onCreate() {
cpath=ContactsContract.Contacts.CONTENT_URI;
// some action
nfm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int NOTIFICATION_ID = 1;
Intent intent = new Intent();
PendingIntent pi = PendingIntent.getActivity(DeleteService.this, 1, intent, 0);
nf=new Notification(R.drawable.ic_launcher,"Contact Database changed",System.currentTimeMillis());
nf.setLatestEventInfo(getApplicationContext(), "Delete Event", "contact name", pi);
nf.flags = nf.flags |
Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, nf);
}
@Override
public void onDestroy() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Launch a background thread to do processing.
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
public class LocalBinder extends Binder {
DeleteService getService() {
return DeleteService.this;
}
}
}
當我運行這個程序,並修改接觸它顯示通知首次 如果我幾秒鐘再次修改它不起作用爲什麼請任何人幫我
具有從開機啓動的前臺服務有點24X7服務。 – 2016-01-06 02:30:20