2

我的 android 应用程序需要在特定时间安排任务。它可以是每天、每周、每月等。因此,在插入输入数据时,如果用户选择“每天”。会有后台服务,每天都会插入相同的数据。

我试图创建服务和相应的接收器类,但是看起来服务没有自动运行。有人可以告诉我缺少什么吗?

接收器类

     public class MyScheduleReceiver extends BroadcastReceiver {

      // Restart service every 30 seconds
      private static final long REPEAT_TIME = 1000 * 30;

      @Override
      public void onReceive(Context context, Intent intent) {
        AlarmManager service = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, MyStartServiceReceiver.class);
        PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar cal = Calendar.getInstance();
        // Start 30 seconds after boot completed
        cal.add(Calendar.SECOND, 30);
        //
        // Fetch every 30 seconds
        // InexactRepeating allows Android to optimize the energy consumption
        service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pending);

        // service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
        // REPEAT_TIME, pending);
        Toast.makeText(context, "Receving", Toast.LENGTH_SHORT).show();

      }



   public class MyStartServiceReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, LocalWordService.class);
        context.startService(service);
      }
    } 

Android Menifest.xml

   <service
    android:name=".LocalWordService"
    android:label="LocalWordService" >
    </service>

    <receiver android:name="MyScheduleReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
<receiver android:name="MyStartServiceReceiver" >
</receiver>

现在,当我启动应用程序时,我调用一个活动类,它基本上使用下面的代码调用服务......但每 30 秒后什么都没有发生。

   Intent mServiceIntent = new Intent(this, LocalWordService.class);
        startService(mServiceIntent);

服务等级

    public class LocalWordService extends Service {
private final IBinder mBinder = new MyBinder();
private ArrayList<String> list = new ArrayList<String>();

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(this, "Starting", Toast.LENGTH_SHORT).show();
    Random random = new Random();
    if (random.nextBoolean()) {
        list.add("Linux");
    }
    if (random.nextBoolean()) {
        list.add("Android");
    }
    if (random.nextBoolean()) {
        list.add("iPhone");
    }
    if (random.nextBoolean()) {
        list.add("Windows7");
    }
    if (list.size() >= 20) {
        list.remove(0);
    }
    return Service.START_NOT_STICKY;
    }

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

  public class MyBinder extends Binder {
    LocalWordService getService() {
        return LocalWordService.this;
    }
}

public List<String> getWordList() {
    return list;
}

   }

请指教,缺少什么?

4

3 回答 3

3
Current Alarm Manager state:




 Realtime wakeup (now=2013-02-27 20:32:52):



 RTC_WAKEUP #1: Alarm{412e05f0 type 0 com.android.providers.calendar}
    type=0 when=+20h57m39s289ms repeatInterval=0 count=0
    operation=PendingIntent{412e05e0: PendingIntentRecord{412e04f0 com.androi
roviders.calendar broadcastIntent}}
  RTC_WAKEUP #0: Alarm{41566480 type 0 android}
    type=0 when=+10h56m12s700ms repeatInterval=3725515 count=0
    operation=PendingIntent{4162dbc0: PendingIntentRecord{41591808 android br
castIntent}}
  RTC #1: Alarm{41532120 type 1 android}
    type=1 when=+22h27m7s419ms repeatInterval=0 count=0
    operation=PendingIntent{4154e7c8: PendingIntentRecord{415adb68 android br
castIntent}}
  RTC #0: Alarm{414eb330 type 1 com.android.calendar}
    type=1 when=+3h27m7s419ms repeatInterval=0 count=0
    operation=PendingIntent{414eb320: PendingIntentRecord{4166c020 com.androi
alendar broadcastIntent}}

  Elapsed realtime wakeup (now=+1h5m9s472ms):
  ELAPSED_WAKEUP #1: Alarm{415608e0 type 2 android}
    type=2 when=+56m18s779ms repeatInterval=0 count=0
    operation=PendingIntent{412fbbc0: PendingIntentRecord{412d26f0 android br
castIntent}}
  ELAPSED_WAKEUP #0: Alarm{41b31c20 type 2 com.android.phone}
    type=2 when=+21s200ms repeatInterval=0 count=0
    operation=PendingIntent{41b31c10: PendingIntentRecord{4163fea8 com.androi
hone broadcastIntent}}
  ELAPSED #3: Alarm{41b21d40 type 3 android}
    type=3 when=+22h57m0s588ms repeatInterval=0 count=0
    operation=PendingIntent{41567800: PendingIntentRecord{41b61370 android br
castIntent}}
  ELAPSED #2: Alarm{41b792e8 type 3 android}
    type=3 when=+9m50s528ms repeatInterval=1800000 count=1
    operation=PendingIntent{415af0b0: PendingIntentRecord{41b791c0 android br
castIntent}}
  ELAPSED #1: Alarm{415d6648 type 3 android}
    type=3 when=+7m30s477ms repeatInterval=0 count=0
    operation=PendingIntent{415652b0: PendingIntentRecord{41bba838 android br
castIntent}}
  ELAPSED #0: Alarm{417b4448 type 3 android}
    type=3 when=+7s294ms repeatInterval=0 count=0
    operation=PendingIntent{4162f708: PendingIntentRecord{415c23a0 android br
castIntent}}

  Broadcast ref count: 0

  Alarm Stats:
  android
    20685ms running, 0 wakeups
    65 alarms: act=android.intent.action.TIME_TICK flg=0x40000014
    2 alarms: act=com.android.server.action.NETWORK_STATS_POLL flg=0x14
    6 alarms: act=com.android.server.ThrottleManager.action.POLL flg=0x14
    1 alarms: act=com.android.server.NetworkTimeUpdateService.action.POLL flg
14
  com.android.providers.calendar
    8935ms running, 1 wakeups
    1 alarms: act=com.android.providers.calendar.intent.CalendarProvider2 flg
14
  com.android.phone
    2632ms running, 63 wakeups
    63 alarms: act=com.android.internal.telephony.gprs-data-stall flg=0x14
于 2013-02-28T01:42:28.493 回答
0

创建服务的简单方法。

创建一个类名作为 DocService

     import java.io.File;
     import java.util.ArrayList;
     import android.app.Service;
     import android.content.Intent;
     import android.os.Bundle;
     import android.os.Environment;
     import android.os.IBinder;
     import android.os.ResultReceiver;
     import backup.PostFile;

     public class DocService extends Service{

    Intent intent;
    ArrayList<File>fileList;
    String fileType;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        this.intent = intent;
        fileList = new ArrayList<File>();
        //new PostFile().execute();

        if(intent.hasExtra("doc"))
        {
            fileType = intent.getStringExtra("doc");
            new PostDocFileThread().start();
        }
    }

    class PostDocFileThread extends Thread
    {
        public void run()
        {

            try 
            {
    Thread.sleep(5000);
    //Do your Stuff here.           

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

然后在调用服务的活动中

public class MainActivity extends Activity {

    static Button docBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        docBtn = (Button)findViewById(R.id.backup_documents);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }



    public void onBackupDocumentClick(View v)
    {

            //new BackupDocument().execute();
            docBtn.setEnabled(false);
            Intent i = new Intent("com.example.backuprestore.DocService");
            i.putExtra("doc", "doc");
            i.putExtra("resReceiver", theReceiver);
            startService(i);
            Toast.makeText(getApplicationContext(), "Backup process has been started in background.",Toast.LENGTH_LONG).show();
        }

    }

And Finally declare your service in AndroidManifest XML



<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.backuprestore.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <service android:name="com.example.backuprestore.DocService" >
        <intent-filter>
            <action android:name="com.example.backuprestore.DocService" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </service>
   </application>
于 2013-09-06T08:10:47.873 回答
0

我制作了一个教程来描述它是如何工作的(所有代码都可以下载和描述)。也许它可以帮助你。注意,法语!

http://julien-dumortier.fr/service-et-binding-sous-android/

于 2013-02-22T00:28:16.990 回答