如何制作一个不打扰活动的运行服务?

时间:2011-08-25 10:33:58

标签: java android android-ndk android-manifest android-service

我有一个名为wipeScreen.java的活动

此活动运行wipeService.java,用于擦除Android手机上的短信和联系人。当一个wipeService运行时,我的wipeScreen活动被卡住而无法使用,只显示黑屏,甚至给我一些“强制关闭”等待很长时间..

有没有人知道如何创建一个可以自行工作而不会干扰活动的服务,以便在服务运行时仍然可以使用该活动?

这是我的擦除触发代码:

SPWipe = getSharedPreferences("wipe", 0);
editorSPWipe = SPWipe.edit();
editorSPWipe.putString("wipe", "yes");
editorSPWipe.commit();

intent myIntent = new Intent(ListenSMSservice.this,WipeScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);

这是我的wipeScreen代码:

        SPtempWipe = getSharedPreferences("wipe", 0);
        if (SPtempWipe.getString("wipe","").equalsIgnoreCase("yes"))
        {
            startService(new Intent(LockScreenForm.this, WipeService.class));
            SPWipe = getSharedPreferences("wipe", 0);
            editorSPWipe = SPWipe.edit();
            editorSPWipe.putString("wipe", "no");
            editorSPWipe.commit();
        }

这是我的wipeService代码:

@Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

        wipeSMS();
        wipeContact();
        stopService(new Intent(this, WipeService.class));
    }


    public void wipeSMS()
    {
        Uri uri = Uri.parse("content://sms");
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(uri, null, null, null,
          null);

        while (cursor.moveToNext()) {
            try {
                long thread_id = cursor.getLong(1);
                Uri thread = Uri.parse("content://sms/conversations/"
                   + thread_id);
                getContentResolver().delete(thread, null, null);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    public void wipeContact() {
        // TODO Auto-generated method stub
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        while (cur.moveToNext()) {
            try{
                String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                System.out.println("The uri is " + uri.toString());
                cr.delete(uri, null, null);
            }
            catch(Exception e)
            {
                //System.out.println(e.getStackTrace());
            }
        }
    }

当服务开始删除我的联系人时,wipeScreen活动卡住了,无法使用..请帮我启动此服务而不会干扰wipeScreen活动..谢谢..

1 个答案:

答案 0 :(得分:1)

我认为您可以使用IntentService在单独的线程中运行代码