即使應用程序關閉(殺死),或者即使用戶沒有啓動應用程序,我也希望服務正在運行。我想在安裝應用程序後啓動服務,從這一點開始,服務需要每十分鐘運行一次。需要在evey中持續運行10分鐘的Android服務
雖然我找到了一些解決方案,如
- Android Service needs to run always (Never pause or stop)
- Android - Run a service in background even when app is killed or device rebooted
- How to run android service permanently like system service?
那些沒有工作給我,因爲我在Android的編程新。 如果有任何示例工作源代碼,請向我提供如何開發它的信息。
這裏是我的服務類..
public class MyService extends Service {
MyReceiver receiver = new MyReceiver();
public void onCreate()
{
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
receiver.SetAlarm(this);
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startId)
{
receiver.SetAlarm(this);
}
}
這裏是我的接收機類..
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}catch (Exception e) {
e.printStackTrace();
}
}
public void SetAlarm(Context context)
{
AlarmManager am =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, UploadLocReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
}
我在AndroidManifest.xml文件增值業務及接收器。
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service android:name=".MyService"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
我在主要活動中添加了以下代碼。
Intent service = new Intent(getApplicationContext(), MyService.class);
this.startService(service);
嗨@HirenPatel,我跟着你的代碼。但是,啓動應用程序時會運行一次。如果我關閉/終止應用程序,則服務運行一次。它不會每十分鐘運行一次。我試圖在MyService類的「OnStartCommand」方法中添加日誌消息。 – NML
@NML,是請分享查詢 –
Hi @HirenPatel,我跟着你的代碼。但是,啓動應用程序時會運行一次。如果我關閉/終止應用程序,則服務運行一次。它不會每十分鐘運行一次。我試圖在MyService類的「OnStartCommand」方法中添加日誌消息。 – NML