我们如何在后台完全运行Android服务,没有任何主要活动?如果是,那么如何,我试过广播接收器,但它不能正常工作,任何帮助和建议深表感谢...
答案 0 :(得分:1)
@SuppressWarnings("deprecation")
public class LocationService extends Service {
DBAdapter mDbAdapter;
double distance;
double longitude,latitude;
String to;
String txt_msg;
@Override
public void onCreate() {
Log.i("Background service ", "calls");
recurscall_location_alert();
}
public static double distFrom(double lat1, double lng1, double lat2,
double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
return dist;
}
private void recurscall_location_alert() {
// TODO Auto-generated method stub
new Timer().scheduleAtFixedRate(new TimerTask() {
@SuppressWarnings("deprecation")
@Override
public void run()
{
c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH) + 1;
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMin = c.get(Calendar.MINUTE);
mSec = c.get(Calendar.SECOND);
ConnectionDetector detect_conn=new ConnectionDetector(getApplicationContext());
boolean connect=detect_conn.isConnectingToInternet();
if(connect)
{
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(location==null)
{
}else
{
longitude = location.getLongitude();
latitude = location.getLatitude();
Log.i("Latitude : ", String.valueOf(latitude));
Log.i("longitude : ", String.valueOf(longitude));
}
}
get_latlong();
get_contacts();
Log.d("Location Alert", "Call location Alert");
/* for (int i = 0; i < Tasks.size(); i++)
{
String[] stringdstime = Start_Time.get(i).split(":");
String[] stringsdate = Task_date.get(i).split("-");
int dshour = Integer.parseInt(stringdstime[0]);
int dsmin = Integer.parseInt(stringdstime[1]);
int day = Integer.parseInt(stringsdate[0]);
int month = Integer.parseInt(stringsdate[1]);
double year1 = Double.parseDouble(stringsdate[2]);
Log.i("Entered : ",
String.valueOf(dsmin) + " "
+ String.valueOf(dshour) + " "
+ String.valueOf(day) + " "
+ String.valueOf(month) + " "
+ String.valueOf(year1));
Log.i("Calendar : ",
String.valueOf(mMin) + " "
+ String.valueOf(mHour) + " "
+ String.valueOf(mDay) + " "
+ String.valueOf(mMonth));
if(year1 == mYear && month == mMonth && day == mDay
&& ( (mHour > dshour)||((mHour == dshour) &&(mMin >= (dsmin)))))
{
Log.i("Date Time: ", "Time Match");
Log.d("ID MATCH=", ids.get(i) + "=="+alertid.get(i));
if(ids.get(i).equals(alertid.get(i)))
{
if(type.get(i).toString().equalsIgnoreCase("EMAIL"))
{
String response = new String();
JSONParser parser = new JSONParser();
Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(getBaseContext())
.getAccounts();
String possibleEmail = "";
to=phone_email.get(i).toString();
txt_msg=content.get(i).toString();
// Account account = accounts[0];
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
possibleEmail = account.name.toString();
}
}
Log.d("Email Address ::", possibleEmail);
if (possibleEmail.trim().length() != 0) {
ConnectionDetector detect=new ConnectionDetector(getApplicationContext());
boolean conn=detect.isConnectingToInternet();
Log.i("Conn", String.valueOf(conn));
if(conn)
{
try{
String temp = "http://122.170.105.226/projects/apps/zealalert/email.php?to="+to+"&from="+possibleEmail+"&message="+txt_msg+"";
temp = temp.replaceAll(" ", "%20");
response = parser.getJSONFromUrlbyGEt(temp);
System.out.println("Response Zeal Alert" + response);
}
catch(Exception e)
{
}
}
}
mDbAdapter=new DBAdapter(getApplicationContext());
mDbAdapter.open();
mDbAdapter.updateDeletedTask(ids.get(i), "1");
}
else if(type.get(i).toString().equalsIgnoreCase("SMS"))
{
to=phone_email.get(i).toString();
txt_msg=content.get(i).toString();
try{
SmsManager manager=SmsManager.getDefault();
manager.sendTextMessage(to, null, txt_msg, null, null);
}catch(Exception e)
{
}
mDbAdapter=new DBAdapter(getApplicationContext());
mDbAdapter.open();
mDbAdapter.updateDeletedTask(ids.get(i), "1");
}
else
{
mDbAdapter=new DBAdapter(getApplicationContext());
mDbAdapter.open();
mDbAdapter.updateDeletedTask(ids.get(i), "1");
}
}
}
}*/
isOutside = new boolean[Tasks.size()];
StringBuilder sb=new StringBuilder();
boolean isTimeAlert=false;
int j=0;
for (int i = j; i < Tasks.size(); i++) {
Log.i("Length : ", String.valueOf(Tasks.size()));
distance = distFrom(latitude, longitude, lat_array.get(i),
long_array.get(i));
double km = distance / 0.62137;
Log.d("KM", String.valueOf(km));
String[] stringdstime = Start_Time.get(i).split(":");
String[] stringsdate = Task_date.get(i).split("-");
int dshour = Integer.parseInt(stringdstime[0]);
int dsmin = Integer.parseInt(stringdstime[1]);
int day = Integer.parseInt(stringsdate[0]);
int month = Integer.parseInt(stringsdate[1]);
double year1 = Double.parseDouble(stringsdate[2]);
Log.i("Entered : ",
String.valueOf(dsmin) + " "
+ String.valueOf(dshour) + " "
+ String.valueOf(day) + " "
+ String.valueOf(month) + " "
+ String.valueOf(year1));
Log.i("Calendar : ",
String.valueOf(mMin) + " "
+ String.valueOf(mHour) + " "
+ String.valueOf(mDay) + " "
+ String.valueOf(mMonth));
if (dsmin < 10){
dsmin += 60;
dshour-=1;}
if (radius_array.get(i) >= km) {
Log.i("Alert : ", "You are in Range...." + ids.get(i));
isOutside[i]=true;
Intent intent = new Intent(LocationService.this,LocationAlert.class);
intent.putExtra("idloc", ids.get(i));
intent.putExtra("taskname", Tasks.get(i).toString());
intent.putExtra("distance", String.valueOf(km));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// stopService(intent);
startActivity(intent);
if(j == Tasks.size()-1)
{
j=0;
}
else
{
j++;
}
}
}
}
}, 3000, 180 * 1000);
}
void get_latlong() {
mDbAdapter = new DBAdapter(getApplicationContext());
mDbAdapter.read_open();
Cursor cr = mDbAdapter.fetchAllTasks();
cr.moveToFirst();
ids.clear();
Tasks.clear();
Priority.clear();
lat_array.clear();
long_array.clear();
radius_array.clear();
Start_Time.clear();
Task_date.clear();
Desc.clear();
while (!cr.isAfterLast()) {
ids.add(Integer.parseInt(cr.getString(0)));
Tasks.add(cr.getString(1));
Priority.add(cr.getString(2));
Task_date.add(cr.getString(3));
Start_Time.add(cr.getString(5));
lat_array.add(Double.valueOf(cr.getString(6)));
long_array.add(Double.valueOf(cr.getString(7)));
radius_array.add(Double.parseDouble(cr.getString(8)));
cr.moveToNext();
}
cr.close();
mDbAdapter.close();
Log.d("LatLongs::", "Lattitude:" + String.valueOf(lat_array)
+ "long_array:" + String.valueOf(long_array));
//get_contacts();
}
public void get_contacts() {
mDbAdapter = new DBAdapter(getApplicationContext());
mDbAdapter.read_open();
Cursor cr2 = mDbAdapter.fetchAllTaskContacts();
cr2.moveToFirst();
alertid.clear();
phone_email.clear();
type.clear();
content.clear();
while (!cr2.isAfterLast()) {
alertid.add(Integer.parseInt(cr2.getString(0)));
phone_email.add(cr2.getString(2));
type.add(cr2.getString(3));
content.add(cr2.getString(4));
cr2.moveToNext();
}
cr2.close();
mDbAdapter.close();
Log.d("Contacts", String.valueOf(alertid) + phone_email + type
+ content);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
答案 1 :(得分:0)
Android文档非常适合创建后台服务。
http://developer.android.com/training/run-background-service/create-service.html