私はGPSトラッカーアプリケーションに取り組んでいます。私のアプリケーションはバックグラウンドで動作し、メニューでユーザーに表示されないようにする必要があります..したがって、基本的に何が起こるかは、phpサーバーに緯度と経度の値を投稿することです..そして、私のアプリケーションは午前9時から午前9時まで手動で開始および停止する必要がありますユーザーとのやり取りのない夜の午後 9 時..ブロードキャスト レシーバーとサービスを使用してアプリケーションをバックグラウンドで実行しています。レシーバーからサービス クラスにインテントを渡していますが、サービス クラスが呼び出されないという問題があります。
これが私のコードです..放送受信機用
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "MyReceiver Started"+intent.getAction(), Toast.LENGTH_SHORT).show();
Intent myIntent=new Intent(context,GPSTRACKER.class);
context.startService(myIntent);
}}
そして、ここにサービスコードがあります..GPSTRACKER
public class GPSTracker extends Service implements LocationListener {
private static String url_create_product = "http://testingicon.com/gps.php";
private static final String TAG_SUCCESS = "success";
JSONparser1 jsonParser2=new JSONparser1();
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;//1 meter
private static final long MIN_TIME_BW_UPDATES = 5000;//30
protected LocationManager locationManager;
private static final String TAG = "BroadcastGPSService";
public static final String BROADCAST_ACTION = "com.example.gpstracking.display";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
int hour,min,year,month,day;
GeoPoint gp;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();}}}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}}}}}} catch (Exception e) {e.printStackTrace();}return location;}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);}}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();}
// return latitude
return latitude;}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();}
// return longitude
return longitude;}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();}});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
//getLocation();
latitude=location.getLatitude();
longitude=location.getLongitude();
gp = new GeoPoint((int)(latitude*1000000), (int)(longitude*1000000));
String address = ConvertPointToLocation(gp);
String locationname = address.substring(0,address.length());
Date date = new Date();
//formatting time to have AM/PM text using 'a' format
String strDateFormat = "HH:mm:ss a";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
String time=sdf.format(date);
String device_id=getdeviceid(mContext);
System.out.println("Time with AM/PM field : " + time);
System.out.println("Location changed is.................. "+latitude+longitude + "Time is "+time +"Date is "+date );
Toast.makeText(mContext, "Location changed is.................. "+"Latitude " +latitude+ "Logitude "+longitude + "Time is "+time +"Date is "+date, Toast.LENGTH_LONG).show();
Log.d(TAG, "entered DisplayLoggingInfo"+ " Time is "+time+ "Date is "+ date + "Device Id iss "+device_id );
String str1=String.valueOf(longitude);
String str2=String.valueOf(latitude);
// here is the code for Posting values on PHP server
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("longitude", str1));
params.add(new BasicNameValuePair("latitude", str2));
params.add(new BasicNameValuePair("time", time));
params.add(new BasicNameValuePair("device_id", device_id));
params.add(new BasicNameValuePair("location_name", locationname));
JSONArray json1=jsonParser2.makeHttpRequest(url_create_product, "POST", params);
// check log cat fro response
// Log.d("Create Response", json.toString());
// check for success tag
/* try {
int success = json1.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// closing this screen
} else {
// failed to create product
}} catch (JSONException e) {
e.printStackTrace();}*/
//db code
}
private String ConvertPointToLocation(GeoPoint gp2) {
// TODO Auto-generated method stub
String address = "";
Geocoder geoCoder = new Geocoder(mContext, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(gp2.getLatitudeE6() / 1E6, gp2.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";}}
catch (IOException e) {
e.printStackTrace();}
return address;}
protected String getdeviceid(Context context2) {
// TODO Auto-generated method stub
TelephonyManager manager = (TelephonyManager)context2.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId;
if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
//Tablet
deviceId = Secure.getString(this.getContentResolver(),
Secure.ANDROID_ID);
} else {
//Mobile
deviceId = manager.getDeviceId();
}
return deviceId;
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;}}
ここにマニフェストファイルがあります
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.websmithing.broadcasttest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<receiver
android:enabled="true"
android:name=".MainActivity">
<!-- <intent-filter>
<action android:name = "com.websmithing.broadcasttest.BroadcastService"/>
</intent-filter> -->
</receiver>
<service android:name=".GPSTRACKER" />
</application>
</manifest>