Androidは高徳地図の地理的フェンスを使って自動的にメールを送信します
53147 ワード
機能点:高徳地図を用いて地理的フェンス機能 を実現は、携帯電話番号とメールの間隔を設定、現在位置 を後間隔で送信することができる.地図選択点設置地理フェンス 地理的フェンスを離れると、対応するメールの注意(携帯電話番号を設定して権限を取得した後) があります.
キーコード
ソースアドレス
Andoroid地理フェンスの位置決めと通知メールの送信
に注意
コードをダウンロードして実行した地図が表示されない場合は、高徳オープンプラットフォームでアカウントを登録し、アプリケーションを申請した後、リストファイルAndroidManifest.xml高徳地図のkeyを再パッケージして実行すればいい.
キーコード
public class MainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener,
GeoFenceListener,
AMap.OnMapClickListener,
LocationSource,
AMapLocationListener,
CompoundButton.OnCheckedChangeListener {
private View lyOption;
private TextView tvGuide;
private TextView tvResult;
private EditText etRadius;
private CheckBox cbAlertIn;
private CheckBox cbAlertOut;
private CheckBox cbAldertStated;
private Button btAddFence;
private Button btOption;
private AMapLocationClient mlocationClient;
private LocationSource.OnLocationChangedListener mListener;
private AMapLocationClientOption mLocationOption;
private MapView mMapView;
private AMap mAMap;
//
private LatLng centerLatLng = null;
// marker
private Marker centerMarker;
private BitmapDescriptor ICON_YELLOW = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW);
private BitmapDescriptor ICON_RED = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED);
private MarkerOptions markerOption = null;
private List markerList = new ArrayList();
// ,
private LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
//
private GeoFenceClient fenceClient = null;
//
private float fenceRadius = 0.0F;
// ,
private int activatesAction = GeoFenceClient.GEOFENCE_IN;
// action
private static final String GEOFENCE_BROADCAST_ACTION = "com.example.geofence.round";
//
private HashMap fenceMap = new HashMap();
private View map_top;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
initView();
initMap(savedInstanceState);
}
private void requestPermission() {
Acp.getInstance(this).request(new AcpOptions.Builder()
.setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE)
.build(),
new AcpListener() {
@Override
public void onGranted() {
}
@Override
public void onDenied(List permissions) {
ToastUtil.show(MainActivity.this," , ");
}
});
}
private void initView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView user = (TextView) headerView.findViewById(R.id.user_textview);
String userid = SpUtil.getString(ConstantValue.USER_LOGIN_INFO, "");
user.append(userid+"");
}
private void sendMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
showMissingPermissionDialog();
}else{
//
startMessage();
}
}
private void showMissingPermissionDialog() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle(R.string.notifyTitle);
builder.setMessage(R.string.notifyMsg);
// ,
builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setPositiveButton(R.string.setting,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.setCancelable(false);
builder.show();
}
private void startMessage() {
handler.post(runnable);
}
private int sendMessageDelay = 60000;
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//
handler.postDelayed(this, 60000);
send(" ");
}
};
private void send(String message) {
if(TextUtils.isEmpty(phone)) {
ToastUtil.show(this," , !");
return;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ToastUtil.show(this," ");
}else{
SmsManager smsManager = SmsManager.getDefault();
Log.e("tag",""+currentLocation.length());
smsManager.sendTextMessage(phone,"",message+currentLocation+"",null,null);
ToastUtil.show(this," ");
}
}
/**
*
*
* @since 2.5.0
*
*/
private void startAppSettings() {
Intent intent = new Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
private void initMap(Bundle savedInstanceState) {
//
fenceClient = new GeoFenceClient(getApplicationContext());
tvResult = (TextView)findViewById(R.id.tv_result);
tvResult.setVisibility(View.GONE);
showSetMapDialog = new Dialog(this);
View view = LayoutInflater.from(this).inflate(R.layout.plugin_geofence_option, null);
showSetMapDialog.setContentView(view);
map_top = view.findViewById(R.id.map_top);
lyOption = view.findViewById(R.id.ly_option);
btAddFence = (Button) view.findViewById(R.id.bt_addFence);
btOption = (Button) view.findViewById(R.id.bt_option);
tvGuide = (TextView) view.findViewById(R.id.tv_guide);
etRadius = (EditText) view.findViewById(R.id.et_radius);
cbAlertIn = (CheckBox) view.findViewById(R.id.cb_alertIn);
cbAlertOut = (CheckBox) view.findViewById(R.id.cb_alertOut);
cbAldertStated = (CheckBox) view.findViewById(R.id.cb_alertStated);
mMapView = (MapView) findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
markerOption = new MarkerOptions().draggable(true);
init();
String username = SpUtil.getString(ConstantValue.USER_LOGIN_INFO,"");
List users = DataSupport.where("username = ? ", username).find(User.class);
if (users!=null && users.size()>0) {
try{
User user = users.get(0);
phone = user.getSendMessagePhone();
sendMessageDelay = Integer.parseInt(user.getSendMessageDelay());
}catch (Exception e) {
}
}
}
private Dialog showSetMapDialog;
private void showSetMapDialog() {
if(showSetMapDialog.isShowing()) {
showSetMapDialog.dismiss();
}else {
showSetMapDialog.show();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_zhuxiao) {
SpUtil.putInt(ConstantValue.USER_LOGIN_INFO,0);
ToastUtil.show(this," , ");
startActivity(new Intent(this, LoginActivity.class));
finish();
return true;
}
if(id==R.id.action_exit) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_phone) {
showPhoneDialog();
}else if(id == R.id.nav_weilan) {
showSetMapDialog();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private String phone;
private void showPhoneDialog() {
final EditText et = new EditText(this);
et.setHint("11 ");
if(!TextUtils.isEmpty(phone)) {
et.setText(phone);
}
final EditText et1 = new EditText(this);
et1.setHint(" (s)");
et1.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.addView(et);
linearLayout.addView(et1);
linearLayout.setOrientation(LinearLayout.VERTICAL);
new AlertDialog.Builder(this).setTitle(" ")
.setView(linearLayout)
.setPositiveButton(" ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String input = et.getText().toString();
if (input.equals("")) {
Toast.makeText(getApplicationContext(), " !" + input, Toast.LENGTH_LONG).show();
}
else {
phone = input;
String number = et1.getText().toString();
try{
int delay = Integer.parseInt(number);
sendMessageDelay = delay * 1000;
ToastUtil.show(MainActivity.this," ");
String username = SpUtil.getString(ConstantValue.USER_LOGIN_INFO,"");
List users = DataSupport.where("username = ? ", username).find(User.class);
if (users!=null && users.size()>0) {
User user = users.get(0);
user.setSendMessagePhone(phone);
user.setSendMessageDelay(sendMessageDelay+"");
user.update(user.getId());
}
}catch (Exception e) {
ToastUtil.show(MainActivity.this," ");
}
}
}
})
.setNegativeButton(" ", null)
.show();
}
void init() {
if (mAMap == null) {
mAMap = mMapView.getMap();
mAMap.getUiSettings().setRotateGesturesEnabled(false);
mAMap.moveCamera(CameraUpdateFactory.zoomBy(6));
setUpMap();
}
btOption.setVisibility(View.VISIBLE);
btOption.setText(getString(R.string.hideOption));
resetView_round();
btAddFence.setOnClickListener(this);
btOption.setOnClickListener(this);
cbAlertIn.setOnCheckedChangeListener(this);
cbAlertOut.setOnCheckedChangeListener(this);
cbAldertStated.setOnCheckedChangeListener(this);
IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(GEOFENCE_BROADCAST_ACTION);
registerReceiver(mGeoFenceReceiver, filter);
/**
* pendingIntent
*/
fenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
fenceClient.setGeoFenceListener(this);
/**
* ,
*/
fenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN);
}
/**
* amap
*/
private void setUpMap() {
mAMap.setOnMapClickListener(this);
mAMap.setLocationSource(this);//
mAMap.getUiSettings().setMyLocationButtonEnabled(true);//
//
MyLocationStyle myLocationStyle = new MyLocationStyle();
//
myLocationStyle.myLocationIcon(
BitmapDescriptorFactory.fromResource(R.drawable.gps_point));
//
myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
//
myLocationStyle.strokeWidth(0);
//
myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
// myLocationStyle
mAMap.setMyLocationStyle(myLocationStyle);
mAMap.setMyLocationEnabled(true);// true ,false , false
// , 、
mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
}
/**
*
*/
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
/**
*
*/
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
/**
*
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
/**
*
*/
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
handler.removeCallbacks(runnable);
handler.removeMessages(1);
handler.removeMessages(2);
handler.removeMessages(0);
handler = null;
try {
unregisterReceiver(mGeoFenceReceiver);
} catch (Throwable e) {
}
if (null != fenceClient) {
fenceClient.removeGeoFence();
}
if (null != mlocationClient) {
mlocationClient.onDestroy();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_addFence :
addFence();
break;
case R.id.bt_option :
if (btOption.getText().toString()
.equals(getString(R.string.showOption))) {
lyOption.setVisibility(View.VISIBLE);
btOption.setText(getString(R.string.hideOption));
} else {
lyOption.setVisibility(View.GONE);
btOption.setText(getString(R.string.showOption));
}
break;
default :
break;
}
}
private void drawFence(GeoFence fence) {
switch (fence.getType()) {
case GeoFence.TYPE_ROUND :
case GeoFence.TYPE_AMAPPOI :
drawCircle(fence);
break;
case GeoFence.TYPE_POLYGON :
case GeoFence.TYPE_DISTRICT :
drawPolygon(fence);
break;
default :
break;
}
removeMarkers();
}
private void drawCircle(GeoFence fence) {
LatLng center = new LatLng(fence.getCenter().getLatitude(),
fence.getCenter().getLongitude());
//
mAMap.addCircle(new CircleOptions().center(center)
.radius(fence.getRadius()).strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH));
boundsBuilder.include(center);
}
private void drawPolygon(GeoFence fence) {
final List> pointList = fence.getPointList();
if (null == pointList || pointList.isEmpty()) {
return;
}
for (List subList : pointList) {
List lst = new ArrayList();
PolygonOptions polygonOption = new PolygonOptions();
for (DPoint point : subList) {
lst.add(new LatLng(point.getLatitude(), point.getLongitude()));
boundsBuilder.include(
new LatLng(point.getLatitude(), point.getLongitude()));
}
polygonOption.addAll(lst);
polygonOption.strokeColor(Const.STROKE_COLOR)
.fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH);
mAMap.addPolygon(polygonOption);
}
}
Object lock = new Object();
void drawFence2Map() {
new Thread() {
@Override
public void run() {
try {
synchronized (lock) {
if (null == fenceList || fenceList.isEmpty()) {
return;
}
for (GeoFence fence : fenceList) {
if (fenceMap.containsKey(fence.getFenceId())) {
continue;
}
drawFence(fence);
fenceMap.put(fence.getFenceId(), fence);
}
}
} catch (Throwable e) {
}
}
}.start();
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0 :
StringBuffer sb = new StringBuffer();
sb.append(" ");
Toast.makeText(getApplicationContext(), sb.toString(),
Toast.LENGTH_SHORT).show();
showSetMapDialog();
drawFence2Map();
break;
case 1 :
int errorCode = msg.arg1;
Toast.makeText(getApplicationContext(),
" " + errorCode, Toast.LENGTH_SHORT).show();
break;
case 2 :
String statusStr = (String) msg.obj;
tvResult.setVisibility(View.VISIBLE);
tvResult.append(statusStr + "
");
break;
default :
break;
}
}
};
List fenceList = new ArrayList();
@Override
public void onGeoFenceCreateFinished(final List geoFenceList,
int errorCode, String customId) {
Message msg = Message.obtain();
if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {
fenceList = geoFenceList;
msg.obj = customId;
msg.what = 0;
} else {
msg.arg1 = errorCode;
msg.what = 1;
}
handler.sendMessage(msg);
}
/**
* , , , ;
* , , 。
*/
private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//
if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
Bundle bundle = intent.getExtras();
String customId = bundle
.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
//status ,
int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
StringBuffer sb = new StringBuffer();
switch (status) {
case GeoFence.STATUS_LOCFAIL :
sb.append(" ");
break;
case GeoFence.STATUS_IN :
sb.append(" ");
send(" ");
break;
case GeoFence.STATUS_OUT :
sb.append(" ");
send(" ");
break;
case GeoFence.STATUS_STAYED :
sb.append(" ");
break;
default :
break;
}
if(status != GeoFence.STATUS_LOCFAIL){
if(!TextUtils.isEmpty(customId)){
sb.append(" customId: " + customId);
}
sb.append(" fenceId: " + fenceId);
}
String str = sb.toString();
Message msg = Message.obtain();
msg.obj = str;
msg.what = 2;
handler.sendMessage(msg);
}
}
};
@Override
public void onMapClick(LatLng latLng) {
markerOption.icon(ICON_YELLOW);
centerLatLng = latLng;
addCenterMarker(centerLatLng);
tvGuide.setBackgroundColor(getResources().getColor(R.color.gary));
tvGuide.setText(" :" + centerLatLng.longitude + ","
+ centerLatLng.latitude);
}
/**
*
*/
private String currentLocation = " ";
@Override
public void onLocationChanged(AMapLocation location) {
if (mListener != null && location != null) {
StringBuffer sb = new StringBuffer();
//errCode 0 , ,
if(location.getErrorCode() == 0){
mListener.onLocationChanged(location);//
sb.append(" " + "
");
sb.append(" : " + location.getLongitude() );
sb.append(" : " + location.getLatitude() + "
");
sb.append(" : " + location.getAddress() + "
");
} else {
//
sb.append(" " + "
");
sb.append(" :" + location.getErrorCode() + "
");
sb.append(" :" + location.getErrorInfo() + "
");
sb.append(" :" + location.getLocationDetail() + "
");
}
// ,
String result = sb.toString();
currentLocation = " :"+location.getLatitude()+" :"+location.getLatitude()+" :"+location.getAddress();
tvResult.setText(result+"
");
currentLocation.replace("
","");
Log.e("tag","result: "+result);
}
}
/**
*
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mlocationClient == null) {
mlocationClient = new AMapLocationClient(this);
mLocationOption =getDefaultOption();
//
mlocationClient.setLocationListener(this);
/* //
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
// ,
mLocationOption.setOnceLocation(false);*/
//
mlocationClient.setLocationOption(mLocationOption);
mlocationClient.startLocation();
Log.e("tag","startlocation");
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent home = new Intent(Intent.ACTION_MAIN);
home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
home.addCategory(Intent.CATEGORY_HOME);
startActivity(home);
return true;
}
return super.onKeyDown(keyCode, event);
}
private AMapLocationClientOption getDefaultOption(){
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);// , , 、 、 。
mOption.setGpsFirst(true);// , gps , 。
mOption.setHttpTimeOut(30000);// , 。 30 。
mOption.setInterval(5000);// , 。 2
mOption.setNeedAddress(true);// , 。 true
mOption.setOnceLocation(false);// , 。 false
mOption.setOnceLocationLatest(false);// , wifi , false. true, ,
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);// , 。 HTTP HTTPS。 HTTP
mOption.setSensorEnable(false);// , 。 false
mOption.setWifiScan(true); // , wifi 。 true, false , ,
mOption.setLocationCacheEnable(true); // , , true
return mOption;
}
/**
*
*/
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
private void addCenterMarker(LatLng latlng) {
if (null == centerMarker) {
centerMarker = mAMap.addMarker(markerOption);
}
centerMarker.setPosition(latlng);
markerList.add(centerMarker);
}
private void removeMarkers() {
if(null != centerMarker){
centerMarker.remove();
centerMarker = null;
}
if (null != markerList && markerList.size() > 0) {
for (Marker marker : markerList) {
marker.remove();
}
markerList.clear();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.cb_alertIn :
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_IN;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_OUT
| GeoFenceClient.GEOFENCE_STAYED);
}
break;
case R.id.cb_alertOut :
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_OUT;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_IN
| GeoFenceClient.GEOFENCE_STAYED);
}
break;
case R.id.cb_alertStated :
if (isChecked) {
activatesAction |= GeoFenceClient.GEOFENCE_STAYED;
} else {
activatesAction = activatesAction
& (GeoFenceClient.GEOFENCE_IN
| GeoFenceClient.GEOFENCE_OUT);
}
break;
default :
break;
}
if (null != fenceClient) {
fenceClient.setActivateAction(activatesAction);
}
}
private void resetView_round() {
etRadius.setHint(" ");
etRadius.setVisibility(View.VISIBLE);
tvGuide.setBackgroundColor(getResources().getColor(R.color.red));
tvGuide.setText(" ");
tvGuide.setVisibility(View.VISIBLE);
}
/**
*
*
* @since 3.2.0
* @author hongming.wang
*
*/
private void addFence() {
addRoundFence();
}
/**
*
*
* @since 3.2.0
* @author hongming.wang
*
*/
private void addRoundFence() {
fenceClient.removeGeoFence();
String radiusStr = etRadius.getText().toString();
if (null == centerLatLng
|| TextUtils.isEmpty(radiusStr)) {
Toast.makeText(getApplicationContext(), " ", Toast.LENGTH_SHORT)
.show();
return;
}
DPoint centerPoint = new DPoint(centerLatLng.latitude,
centerLatLng.longitude);
fenceRadius = Float.parseFloat(radiusStr);
fenceClient.addGeoFence(centerPoint, fenceRadius, "1");
}
}
ソースアドレス
Andoroid地理フェンスの位置決めと通知メールの送信
に注意
コードをダウンロードして実行した地図が表示されない場合は、高徳オープンプラットフォームでアカウントを登録し、アプリケーションを申請した後、リストファイルAndroidManifest.xml高徳地図のkeyを再パッケージして実行すればいい.
data
android:name="com.amap.api.v2.apikey"
android:value=" key" />