我是 android 新手,我正在开发我的第一个基于位置的提醒应用程序,我正在添加包含位置、日期和时间的任务,当我到达时应该通知我。我有一个位置开关按钮,如果在我到达该位置时设置为打开,我应该收到通知,如果触发警报将显示位置和日期和时间。我可以只提供警报的位置,也可以提供警报的位置和日期和时间。
布局 :-
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/relative1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bckgrnd_4">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Task Name"
android:id="@+id/textView5"
android:layout_alignBottom="@+id/taskname"
android:layout_alignStart="@+id/textView6" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/taskname"
android:hint="@string/hint_name"
android:layout_marginTop="37dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="@+id/textView7"
>
<requestFocus />
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:id="@+id/button5"
android:onClick="set_loc"
style="@style/btnStyleBeige"
android:layout_marginTop="37dp"
android:layout_below="@+id/textView5"
android:layout_alignStart="@+id/switch1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Set Location"
android:id="@+id/textView6"
android:layout_alignBottom="@+id/button5"
android:layout_toStartOf="@+id/taskname" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Always alert me"
android:id="@+id/textView7"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"/>
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/btnStyleBeige"
android:id="@+id/switch1"
android:layout_alignTop="@+id/textView7"
android:layout_alignEnd="@+id/relative3" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/relative2"
android:layout_marginTop="37dp"
android:layout_below="@+id/switch1"
android:layout_alignParentStart="true">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pickDate"
android:src="@drawable/cal"
style="@style/btnStyleBeige"
android:layout_marginStart="42dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pickTime"
style="@style/btnStyleBeige"
android:src="@drawable/alert"
android:layout_marginStart="67dp"
android:layout_alignBottom="@+id/pickDate"
android:layout_toEndOf="@+id/pickDate" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/relative3"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Add Task"
android:onClick="add_task"
android:drawableLeft="@drawable/add"
style="@style/btnStyleBeige"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button3"
android:text="Cancel"
android:onClick="cancel"
android:drawableLeft="@drawable/bck"
style="@style/btnStyleBeige"
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/button2"
android:layout_marginStart="37dp" />
</RelativeLayout>
活动 :-
public class AddTasks extends Activity implements CompoundButton.OnCheckedChangeListener{
TaskForm activityForm = new TaskForm();
private ImageButton pPickDate;
private int pYear;
private int pMonth;
private int pDay;
public String date;
public String Loc;
public double lat;
public double lon;
private ImageButton pPickTime;
private int mHour;
private int mMinute;
public String time;
private TimePickerDialog timePickerDialog;
private DatePickerDialog datePickerDialog;
Date selectedDate;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;
/** Callback received when the user "picks" a date in the dialog */
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDate();
displayDateToast();
}
};
private TimePickerDialog.OnTimeSetListener mTimeListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hour, int minute) {
mHour = hour;
mMinute = minute;
updateTime();
displayTimeToast();
}
};
/** Updates the date in the TextView */
private void updateDate() {
/** pDisplayDate.setText( */ date =
new StringBuilder()
// Month is 0 based so add 1
.append(pDay).append("/")
.append(pMonth + 1).append("/")
.append(pYear).append(" ").toString();
// date = pDisplayDate.getText().toString();
}
private void updateTime() {
/** pDisplayTime.setText( */ time =
new StringBuilder()
.append(mHour).append(":")
.append(mMinute).append("").toString();
}
/** Displays a notification when the date is updated */
private void displayDateToast() {
//Toast.makeText(this, new StringBuilder().append("Date choosen is ").append(date), Toast.LENGTH_LONG).show();
activityForm.setTaskDateInput(date);
}
private void displayTimeToast() {
// Toast.makeText(this, new StringBuilder().append("Time choosen is ").append(time), Toast.LENGTH_LONG).show();
activityForm.setTaskTimeInput(time);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
RelativeLayout relativeLayout2 = (RelativeLayout)findViewById(R.id.relative2);
if(isChecked) {
relativeLayout2.setVisibility(View.GONE);
} else {
relativeLayout2.setVisibility(View.VISIBLE);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask);
getActionBar().setDisplayHomeAsUpEnabled(true);
Switch aSwitch = (Switch) findViewById(R.id.switch1);
RelativeLayout relativeLayout1 = (RelativeLayout)findViewById(R.id.relative1);
RelativeLayout relativeLayout3 = (RelativeLayout)findViewById(R.id.relative3);
aSwitch.setOnCheckedChangeListener(this);
init();
/** Capture our View elements */
//pDisplayDate = (TextView) findViewById(R.id.displayDate);
pPickDate = (ImageButton) findViewById(R.id.pickDate);
/** Listener for click event of the button */
pPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
/** Capture our View elements */
//pDisplayTime = (TextView) findViewById(R.id.displayTime);
pPickTime = (ImageButton) findViewById(R.id.pickTime);
/** Listener for click event of the button */
pPickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
/** Get the current date and time */
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
mHour = cal.get(Calendar.HOUR_OF_DAY);
mMinute = cal.get(Calendar.MINUTE);
}
/** Create a new dialog for date and time picker */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
datePickerDialog = new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
Date dt = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
mHour = calendar.get(Calendar.HOUR_OF_DAY);
mMinute = calendar.get(Calendar.MINUTE);
datePickerDialog.getDatePicker().setMinDate(dt.getTime() - 10000);
// datePickerDialog.getDatePicker().setMinDate(new Date().getTime() - 10000);
return datePickerDialog;
case TIME_DIALOG_ID:
timePickerDialog = new TimePickerDialog(this,
mTimeListener,
mHour,mMinute,true) ;
return timePickerDialog;
}
return null;
}
public void set_loc(View v)
{
Intent i = new Intent(this, Set_Location.class);
startActivityForResult(i, 2);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
try {
lat = data.getDoubleExtra("lat", 0.0);
lon = data.getDoubleExtra("lon", 0.0);
String loc_name = data.getStringExtra("loc");
//Toast.makeText(getApplicationContext(), "loc " + lat + ":" + lon,
// Toast.LENGTH_LONG).show();
// Loc = String.valueOf(lat) + String.valueOf(lon);
Loc = loc_name;
// Toast.makeText(getApplicationContext(),"Loc : " + loc_name,Toast.LENGTH_LONG).show();
activityForm.setTaskLocInput(Loc);
activityForm.setTaskLat(lat);
activityForm.setTaskLon(lon);
}
catch(NullPointerException e) {
Log.e("Null", "Null");
}
}
}
private void persistTask(Task task) {
FileOutputStream fileOutputStream;
try {
fileOutputStream = openFileOutput("" + task.hashCode(),
Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
fileOutputStream);
objectOutputStream.writeObject(task);
objectOutputStream.close();
fileOutputStream.close();
} catch (Exception e) {
Log.e("file out", "file out");
}
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
public void add_task(View view) {
if(activityForm.getTaskNameInput().getText() != null ) {
if (activityForm.getTaskLocInput() != null
&& activityForm.getTaskLat() != null && activityForm.getTaskLon() != null)
{
Task task = new Task();
task.setTaskNameString(activityForm.getTaskNameInput().getText()
.toString());
task.setTaskLocString(activityForm.getTaskLocInput());
task.setTaskLat(activityForm.getTaskLat());
task.setTaskLon(activityForm.getTaskLon());
task.setDateString(activityForm.getTaskDateInput());
task.setTimeString(activityForm.getTaskTimeInput());
persistTask(task);
// Toast.makeText(getApplicationContext(), "SAVED=" + task.hashCode(),
// Toast.LENGTH_LONG).show();
activityForm.getTaskNameInput().setText(" ");
Calendar c = Calendar.getInstance();
if (timePickerDialog != null) {
timePickerDialog.updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
}
if (datePickerDialog != null) {
datePickerDialog.updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Attention");
dialog.setMessage("Please select Location");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
dialog.show();
}
}
else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Attention");
dialog.setMessage("Please enter task name");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
dialog.show();
}
}
private void init() {
activityForm
.setTaskNameInput((EditText) findViewById(R.id.taskname));
}
服务 :-
public class LocService extends Service {
LocationManager lm ;
Location location ;
// default 0.0
double lat;
double lon;
String name, loca;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "service wokeup",
Toast.LENGTH_SHORT).show();
if(MainActivity.context != null) {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("",""+ lat + " | " + lon);
}
processTasks();
location = null;
lat = 0.0;
lon = 0.0;
return super.onStartCommand(intent, flags, startId);
}
private void processTasks() {
List<Task> tasks = loadFiles();
if(tasks == null || tasks.size() < 1){
// Toast.makeText(getApplicationContext(),"No Tasks Found",Toast.LENGTH_LONG).show();
}
for (Task task : tasks) {
if (tasks != null && task.alert) {
Log.i("Task is ",task.toString());
//Toast.makeText(getApplicationContext(),"Your Task is " + task.toString(),Toast.LENGTH_LONG).show();
// if in time range
boolean timeRange = true;
// if in loc range
boolean locRange = true;
if(task.getTaskLocString() != null && task.getTaskLat() !=null && task.getTaskLon()!= null) {
float dst = 0.0f;
if (lat > 0.0 && lon > 0.0) {
float[] results = new float[1];
Location.distanceBetween(lat, lon, task.getTaskLat(), task.getTaskLon(), results);
float distanceInMeters = results[0];
dst = distanceInMeters;
Log.i("dist", "" + distanceInMeters);
boolean isWithin5km = distanceInMeters < 5000;
locRange = isWithin5km;
}
Log.i("bool", "" + locRange);
// Toast.makeText(this,"dist is " + dst ,Toast.LENGTH_LONG).show();
if (dst < 5000) {
// Toast.makeText(getApplicationContext(),"Booooom",Toast.LENGTH_LONG).show();
locRange = true;
} else {
locRange = false;
//Toast.makeText(getApplicationContext(),"Faaalse",Toast.LENGTH_LONG).show();
}
}
// Toast.makeText(getApplicationContext(),"Date is " + task.getDateString(),Toast.LENGTH_LONG).show();
if(task.getDateString() != null && task.getTimeString() != null) {
// format date
String datearr[] = task.getDateString().split("/");
int day = Integer.parseInt(datearr[0]);
int month = Integer.parseInt(datearr[1]);
month--;
int year = Integer.parseInt(datearr[2].trim());
// Toast.makeText(getApplicationContext(),"Date is " + datearr,Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),"Time is " + task.getTimeString(),Toast.LENGTH_LONG).show();
//format time
String timearr[] = task.getTimeString().split(":");
if (timearr != null) {
Log.i("=>", timearr.toString());
//Toast.makeText(getApplicationContext(),"Time is " + timearr.toString(),Toast.LENGTH_LONG).show();
} else {
Log.e("tme null", "time null");
// Toast.makeText(getApplicationContext(),"Time is Null",Toast.LENGTH_LONG).show();
}
int hour = Integer.parseInt(timearr[0]);
int minute = Integer.parseInt(timearr[1]);
// month range 0-11
Calendar event = Calendar.getInstance();
event.set(year, month, day, hour, minute);
Calendar now = Calendar.getInstance();
Log.i("event", "" + event.toString());
Log.i("now", "" + now.toString());
int hourNow = now.get(Calendar.HOUR_OF_DAY);
int dNow = now.get(Calendar.DAY_OF_MONTH);
int mNow = now.get(Calendar.MONTH);
int yNow = now.get(Calendar.YEAR);
int minNow = now.get(Calendar.MINUTE);
Log.i("year", "" + yNow + " y " + year);
Log.i("mnth", "" + mNow + " m " + month);
Log.i("day", "" + dNow + " d " + day);
Log.i("minute", "" + minNow + "min" + minute);
if (yNow == year && mNow == month && dNow == day) {
if (hourNow == hour && minNow == minute) {
timeRange = true;
} else {
Log.i("hour", "" + (hour - hourNow));
}
}
}
// Toast.makeText(getApplicationContext(),"Values are :- " + day + " , " + month + " , " + year + " , " + hour + " , " + minute,Toast.LENGTH_LONG).show();
// timeRange = true;
// Toast.makeText(getApplication(),"Time Range is " + timeRange,Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),"Loc Range is " + locRange,Toast.LENGTH_LONG).show();
name = task.getTaskNameString();
loca = task.getTaskLocString();
if (timeRange && locRange) {
Toast.makeText(getApplicationContext(),"Your Task is " + task.toString(),Toast.LENGTH_LONG).show();
// Alertview.TASK_STATIC = task;
Gson gson = new Gson();
String L = gson.toJson(loca);
String N = gson.toJson(name);
Intent intent = new Intent(this, Alertview.class);
intent.putExtra("Loc", L);
intent.putExtra("name",N);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Alert !!!!");
builder.setContentText(" " + name);
builder.setLights(Color.WHITE, 1500, 1500);
builder.setDefaults(Notification.DEFAULT_VIBRATE);
builder.setDefaults(Notification.DEFAULT_LIGHTS);
builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setDefaults(Notification.FLAG_SHOW_LIGHTS);
builder.setContentIntent(pIntent);
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(99, builder.build());
task.alert = false;
persistTask(task);
}
}
}
}
private void persistTask(Task task) {
FileOutputStream fileOutputStream;
try {
fileOutputStream = openFileOutput("" + task.hashCode(),
Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
fileOutputStream);
objectOutputStream.writeObject(task);
objectOutputStream.close();
fileOutputStream.close();
} catch (Exception e) {
Log.e("file out", "file out");
}
}
private List<Task> loadFiles() {
List<Task> tasks = new ArrayList<Task>();
File file = getFilesDir();
File[] files = file.listFiles();
for (File temp : files) {
try {
ObjectInputStream is = new ObjectInputStream(
new FileInputStream(temp));
Task task = (Task) is.readObject();
is.close();
tasks.add(task);
} catch (StreamCorruptedException e) {
Log.e("file read", "file read");
} catch (FileNotFoundException e) {
Log.e("file read", "file read");
} catch (IOException e) {
Log.e("file read", "file read");
} catch (ClassNotFoundException e) {
Log.e("file read", "file read");
}
}
return tasks;
}
}
在上述服务中,首先 m 检查任务的位置是否为空,将 locRange 设置为 true,如果日期时间不为空,则 timeRange 为 true,即此处:-
boolean timeRange = true;
// if in loc range
boolean locRange = true;
if(task.getTaskLocString() != null && task.getTaskLat() !=null && task.getTaskLon()!= null) {
float dst = 0.0f;
if (lat > 0.0 && lon > 0.0) {
float[] results = new float[1];
Location.distanceBetween(lat, lon, task.getTaskLat(), task.getTaskLon(), results);
float distanceInMeters = results[0];
dst = distanceInMeters;
Log.i("dist", "" + distanceInMeters);
boolean isWithin5km = distanceInMeters < 5000;
locRange = isWithin5km;
}
Log.i("bool", "" + locRange);
// Toast.makeText(this,"dist is " + dst ,Toast.LENGTH_LONG).show();
if (dst < 5000) {
// Toast.makeText(getApplicationContext(),"Booooom",Toast.LENGTH_LONG).show();
locRange = true;
} else {
locRange = false;
//Toast.makeText(getApplicationContext(),"Faaalse",Toast.LENGTH_LONG).show();
}
}
// Toast.makeText(getApplicationContext(),"Date is " + task.getDateString(),Toast.LENGTH_LONG).show();
if(task.getDateString() != null && task.getTimeString() != null) {
// format date
String datearr[] = task.getDateString().split("/");
int day = Integer.parseInt(datearr[0]);
int month = Integer.parseInt(datearr[1]);
month--;
int year = Integer.parseInt(datearr[2].trim());
// Toast.makeText(getApplicationContext(),"Date is " + datearr,Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),"Time is " + task.getTimeString(),Toast.LENGTH_LONG).show();
//format time
String timearr[] = task.getTimeString().split(":");
if (timearr != null) {
Log.i("=>", timearr.toString());
//Toast.makeText(getApplicationContext(),"Time is " + timearr.toString(),Toast.LENGTH_LONG).show();
} else {
Log.e("tme null", "time null");
// Toast.makeText(getApplicationContext(),"Time is Null",Toast.LENGTH_LONG).show();
}
int hour = Integer.parseInt(timearr[0]);
int minute = Integer.parseInt(timearr[1]);
// month range 0-11
Calendar event = Calendar.getInstance();
event.set(year, month, day, hour, minute);
Calendar now = Calendar.getInstance();
Log.i("event", "" + event.toString());
Log.i("now", "" + now.toString());
int hourNow = now.get(Calendar.HOUR_OF_DAY);
int dNow = now.get(Calendar.DAY_OF_MONTH);
int mNow = now.get(Calendar.MONTH);
int yNow = now.get(Calendar.YEAR);
int minNow = now.get(Calendar.MINUTE);
Log.i("year", "" + yNow + " y " + year);
Log.i("mnth", "" + mNow + " m " + month);
Log.i("day", "" + dNow + " d " + day);
Log.i("minute", "" + minNow + "min" + minute);
if (yNow == year && mNow == month && dNow == day) {
if (hourNow == hour && minNow == minute) {
timeRange = true;
} else {
Log.i("hour", "" + (hour - hourNow));
}
}
}
完成上述操作后,如果说我添加了 3 个任务:-
- 任务1:-位置> 5公里并且没有日期时间(因为这个m没有得到正确的警报)
- 任务2:- 位置<5km 并且没有日期时间(m 得到警报,这也是正确的)
- Task3 :- Loaction<5km,日期 - 31/5/2015 和时间 - 11:12(对于这个任务,它不检查时间范围条件,即我添加任务的那一刻,比如在 11:05 m 收到警报)
我错过了什么?请帮助我这是我申请的主要部分..