我的应用要求
该应用程序将有一个活动和一个服务。
该服务有一个短信内容观察者。
应用程序安装后,无论应用程序是否处于活动状态,服务都应始终运行
服务内部的 contentobserver 的注册和注销应该由 Activity 控制。
在卸载应用程序时,服务应该被销毁。
我尝试了一些代码。在服务的创建中,我已经对内容观察者进行了重新注册,并且在销毁时我取消了它的注册。我已经使用了活动的启动和停止服务。但即使在停止服务之后,内容观察者的 onchange 方法仍然会被调用。
请让我知道一些示例代码和此服务的清单定义。
public class MyActivity extends ListActivity implements OnInitListener {
@Override
protected void onDestroy() {
super.onDestroy(); // let it be here as per the android TTS samples
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.startService(sintent);
}
private boolean SSMyservice() {
// TODO Auto-generated method stub
//stop service
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.stopService(sintent);
//do some work
//start service again
MyActivity.this.startService(sintent); //start service again
return true;
} //importdata
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.TTSread:
return true;
case R.id.SSS:
SSMyservice();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Log.v(TAG,"option menu created");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.omenu, menu);
return true;
}
}
------------end MyActivity---------------------
----------------------------------
public class MyService extends Service {
protected SmsObserver smsSentObserver=null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate()
{
registersmsevent();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregistersmsevent();
}
public void registersmsevent() {
// TODO Auto-generated method stub
if(smsSentObserver == null)
{
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
smsSentObserver = new SmsObserver(new Handler());
MyService.this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);
}
}
public void unregistersmsevent() {
if(smsSentObserver != null)
{
MyService.this.getContentResolver().unregisterContentObserver(smsSentObserver);
smsSentObserver = null;
}
}
public class SmsObserver extends ContentObserver {
Handler handler;
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
this.handler = handler;
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
//my code........
super.onChange(selfChange);
}
}//End of class SmsObserver
}//end of service