Android服务未在后台正常运行

时间:2013-07-27 15:52:27

标签: android service

一旦我打开我的应用程序,我就开始这一行:

Intent intent = new Intent(this, MyIntentService.class);
        startService(intent);

这是我的IntentService类:

public class MyIntentService extends Service {
    SharedPreferences prefs;
    public static String prefName = "SecretFile";
    public static String version = "56";
    public final static int uniqueID = 1394885;



public void onCreate() {
        super.onCreate();
        prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
        version = prefs.getString("Version", "1");
        System.out.println(version);
        calllsharedprefs();
        new loadSomeStuff().execute();
    }

public class loadSomeStuff extends AsyncTask<String, Integer, String> {

    protected void onPreExecute() {

    }

        @Override
        protected String doInBackground(String... params) {
//starting script
                    JSONObject json = jArray.getJSONObject(i);
                    json.getString("Version");
                    Editor editoi = prefs.edit();
                    editoi.putString("Version", json.getString("Version"));
//finishing script
        }

        protected void onProgressUpdate(Integer... progress) {

        }

        @SuppressWarnings("deprecation")
        protected void onPostExecute(String result) {
            if (prefs.getString("Version", "1").equals(version)) {
            } else {
                System.out.println(prefs.getString("Version", "1"));
                NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                nm.cancel(uniqueID);
                Intent intent = new Intent(MyIntentService.this, Drawer.class);
                PendingIntent pi = PendingIntent.getActivity(
                        MyIntentService.this, 0, intent, 0);
                String body = "New Updates are available!";
                String title = "Price list changed";
                Notification n = new Notification(
                        R.drawable.about, body,
                        System.currentTimeMillis());
                n.setLatestEventInfo(MyIntentService.this, title, body, pi);
                n.defaults = Notification.DEFAULT_ALL;
                nm.notify(uniqueID, n);
                version = prefs.getString("Version", "1");
            }
        }
    }

基本上,我从phpMyAdmin中的表中获取Version字段,如果版本代码相同,如果它没有发送通知并将其设置为与phpmyadmin版本相同,则不发送通知, 然而,当我打开我的应用程序时,代码启动并向我发送通知,但是当我重新编辑表中的值以将其设置为9时,它无法正常工作#39;再次发送anotificaiton!该怎么办?谢谢=)

1 个答案:

答案 0 :(得分:1)

您在oncreate中调用了&gt;&gt; loadSomeStuff().execute();。 它只会执行一次,并按照你的要求做任何事情。

每次编辑值时都会启动此IntentService,或者在Activity自己编辑值时启动此Activity。您似乎不需要服务,您可以自{{1}}显示通知。