我有下面的代碼,我想每5秒循環一次。我試圖使用廣播接收器和報警管理器,但沒有成功。我希望我的服務循環5次,然後永久停止。這是我發佈的第二個問題。請有人幫我修復代碼,我在我的Mac上堆積了2天。任何幫助將不勝感激。Android循環服務每5秒啓動一次啓動
代碼以循環每5秒
File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
try {
key.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
InfoReceiver.class服務
public class InfoReceiver extends Service {
@Override
public void onCreate()
{
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 5);
alarmMgr.set(AlarmManager.RTC_WAKEUP, 5000, pendingIntent);
}
}
InfoManager.class服務
public class InfoManager extends Service {
@Override
public void onCreate() {
File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
try {
key.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyBroadcastreceiver.class
public class MyBroadcastReceiver extends BroadcastReceiver {
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, InfoManager.class);
context.startService(startServiceIntent);
}
}
清單代碼
<service
android:name=".InfoReceiver"
android:enabled="true" >
</service>
<service
android:name=".InfoManager"
android:enabled="true" >
<intent-filter>
<action android:name=".InfoManager" />
</intent-filter>
</service>
<receiver
android:name=".MyBroadcastReceiver"
android:process=":remote" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
你究竟想要什麼...... 5秒後執行服務na ??? – 2012-03-23 14:29:37
您希望從手機啓動開始每5秒鐘在用戶外部存儲器中創建一個隨機名稱的文件。我們爲什麼要幫你做到這一點? – CaseyB 2012-03-23 14:31:37
我改變它創建一個文件,以便能夠檢查....實際上它不是我想做的工作(創建文件)。但是,對於此代碼,我希望每5秒創建一個文件並在5個循環永久銷燬服務 – rami78 2012-03-23 14:36:16