我想在後臺運行的android中開始一項服務,並且在啓動手機並定期發送消息後立即啓動。我已經編寫了如下代碼一款定期發送短信的android服務
MainActivity.class
package test.sai;
public class MainActivity extends Activity {
Timer t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
alrm();
Log.e("msg", "in main");
}
public void alrm() {
Intent myAlarm = new Intent(getApplicationContext(), AlarmReceiver.class);
Log.e("msg", "in alrm");
//myAlarm.putExtra("project_id", project_id); //Put Extra if needed
PendingIntent recurringAlarm = v PendingIntent.getBroadcast(getApplicationContext(), 0, myAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Calendar updateTime = Calendar.getInstance();
Log.e("msg", "in alrm1");
//updateTime.setWhatever(0);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, recurringAlarm); //you can modify the interval of course
}
}
此類調用AlarmReceiver.class
package test.sai;
public class AlarmReceiver extends BroadcastReceiver
{
GPSTracker gps;
@Override
public void onReceive(Context context, Intent intent)
{
gps = new GPSTracker(context);
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context,MainActivity.class);
pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(pushIntent);
Log.e("pro", "alrmmanager");
}
Intent myService = new Intent(context, FirstService.class);
myService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(myService);
Log.e("msg", "in alrmmanager1");
}
}
最後AlarmReceiver是調用服務類
package test.sai;
public class FirstService extends Service{
Timer t;
int time = 0;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
Log.e("time", time++ +"");
Toast.makeText(this, time+1+"", 500).show();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
現在我想在儘快服務啓動,然後我想使用GPS跟蹤的移動位置和發送消息到另一個mobile.I也有代碼,GPS全球定位系統和短信發送,但我沒有得到如何打電話和在哪裏調用這些methodss,以便我的服務繼續運行,並在一定的interval.please幫助發送消息。
請給出一個使用AlarmManager的詳細代碼 –
你問別人做所有的工作。 @ abhishek-shukla和其他答覆者都指出你在正確的方向,但是你要把它們放在一起。沒有人會爲你寫你的應用程序。 –
@RahatAhmed我已經編輯了上面的問題,現在可以請你指導我進一步。 –