Android 如何从broadcastReceiver调用服务方法?
我有GPS跟踪应用程序的主要目标是每隔5分钟将GPS坐标保存到备份数据库中。所以我创建了Android 如何从broadcastReceiver调用服务方法?,android,Android,我有GPS跟踪应用程序的主要目标是每隔5分钟将GPS坐标保存到备份数据库中。所以我创建了服务和接收器,因为即使我的应用程序没有打开/运行,它也应该可以工作 用户输入执行代码后,创建数据库并进入欢迎屏幕。 在那里,它启动GPS捕获并将其保存到PDA数据库,调用服务上传。我有一个接收器,当手机启动时,它会启动这个接收器和接收器呼叫服务 我的问题是接受者没有呼叫服务。它没有上服务课 protected void onStop(){ super.onStop(); if(gpsRec
服务
和接收器
,因为即使我的应用程序没有打开/运行,它也应该可以工作
用户输入执行代码后,创建数据库并进入欢迎屏幕。
在那里,它启动GPS捕获并将其保存到PDA数据库,调用服务上传。我有一个接收器,当手机启动时,它会启动这个接收器和接收器呼叫服务
我的问题是接受者没有呼叫服务。它没有上服务课
protected void onStop(){
super.onStop();
if(gpsReceiver != null){
unregisterReceiver(gpsReceiver);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
gpsReceiver = new GpsReceiver();
IntentFilter intentFilter1 = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
intentFilter1.addAction(Intent.ACTION_BOOT_COMPLETED);
intentFilter1.addAction(Intent.ACTION_POWER_CONNECTED);
intentFilter1.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(gpsReceiver, intentFilter1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyLocationListener());
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format( "Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude());
longitude = location.getLongitude();
latitude =location.getLatitude();
//save GPS coordinate to PDA DB
GPSDBAdapter dbAdapter = GPSDBAdapter.getDBAdapterInstance(HomeActivity.this);
dbAdapter.openDataBase();
dbAdapter.insertGPS(longitude, latitude, "MASS", deserializeObject());
dbAdapter.close();
//After save GPS coordinate it upload to backend using service
startService(new Intent(HomeActivity.this, UploadService.class));
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(HomeActivity.this, "Provider status changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(HomeActivity.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(HomeActivity.this, "Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
}
这是我的听筒
public class GpsReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
int delay = 5000; // delay for 5 sec.
//int period = 1000 *60*5; // repeat every 5min.
int period = 30000; // repeat every 5min.
//TO-REMOVE -TESTING PURPOSE
Intent serviceIntent = new Intent(context,UploadService.class);
context.startService(serviceIntent);
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(" Receiver done");
Intent serviceIntent = new Intent(context,UploadService.class);
context.startService(serviceIntent);
}
}, delay, period);
}
}
}
这是我的服务
public class UploadService extends Service{
private Thread serviceThread = null;
public static final String APPURL = "http://124.43.25.10:8080/Ornox/GPSPulseReceiver";
public static double longitude;
public static double latitude ;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Log.d("========", "onCreate");
Toast.makeText(UploadService.this, "Upload GPS Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(UploadService.this, "Upload Service Stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(UploadService.this, "Upload Service Started", Toast.LENGTH_LONG).show();
ConnectivityManager manager = (ConnectivityManager) getSystemService(MassGPSTrackingActivity.CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if(is3g ||isWifi){
if(!APPURL.equals("")){
serviceThread = new ServiceThread();
serviceThread.start();
}
}else {
Toast.makeText(this, "GPRS/WIFI is not available", Toast.LENGTH_LONG).show();
}
}
public void uploadGPSData() {
GPSDBAdapter gpsAdapter = GPSDBAdapter.getDBAdapterInstance(this);
gpsAdapter.openDataBase();
try{
String query = " SELECT ExecutiveCode,CaptureDate,CaptureTime,Longitude,Latitude" +//4
" FROM WMLiveGPSData " +
" WHERE UploadFlag ='1' ";
ArrayList<?> stringList = gpsAdapter.selectRecordsFromDBList(query, null);
System.out.println("==WMLiveGPSData==stringList=="+stringList.size());
gpsAdapter.close();
if(stringList.size() > 0){
for (int i = 0; i < stringList.size(); i++) {
ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
ArrayList<?> list = arrayList;
HttpResponse response = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("repc", (String)list.get(0)));
nameValuePairs.add(new BasicNameValuePair("rouc", "SE0160"));
nameValuePairs.add(new BasicNameValuePair("Date", (String)list.get(1)));
nameValuePairs.add(new BasicNameValuePair("Time", (String)list.get(2)));
nameValuePairs.add(new BasicNameValuePair("long", (String)list.get(3)));
nameValuePairs.add(new BasicNameValuePair("lat", (String)list.get(4)));
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000000;
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
int timeoutSocket = 5000000; // in milliseconds which is the timeout
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost method = new HttpPost(APPURL);
// method.setHeader("Content-Type","text/xml");
method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(method);
System.out.println("==response==" + response);
if (response != null) {
Log.i("login",""+ response.getEntity().getContentLength());
} else {
Log.i("login", "got a null response");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect to server. Please Try again",
Toast.LENGTH_SHORT).show();
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
//return response;
}
private class ServiceThread extends Thread {
@Override
public void run() {
uploadGPSData();
}
};
公共类上传服务扩展服务{
私有线程serviceThread=null;
公共静态最终字符串APPURL=”http://124.43.25.10:8080/Ornox/GPSPulseReceiver";
公共静态双经度;
公共静态双纬度;
@凌驾
公共IBinder onBind(意图arg0){
//TODO自动生成的方法存根
返回null;
}
@凌驾
public void onCreate(){
Log.d(“==========”,“onCreate”);
Toast.makeText(UploadService.this,“创建了上载GPS服务”,Toast.LENGTH_LONG.show();
}
@凌驾
公共空间{
Toast.makeText(UploadService.this,“上载服务已停止”,Toast.LENGTH_LONG.show();
}
@凌驾
公共无效启动(Intent Intent,int startid){
Toast.makeText(UploadService.this,“上载服务已启动”,Toast.LENGTH_LONG.show();
ConnectivityManager=(ConnectivityManager)getSystemService(MassGPSTrackingActivity.CONNECTIVITY_服务);
布尔值is3g=manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
布尔值isWifi=manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
如果(is3g | | isWifi){
如果(!APPURL.equals(“”){
serviceThread=新的serviceThread();
serviceThread.start();
}
}否则{
Toast.makeText(此“GPRS/WIFI不可用”,Toast.LENGTH_LONG.show();
}
}
public void uploadGPSData(){
GPSDBAdapter gpsAdapter=GPSDBAdapter.getdbadapterninstance(此);
gpsAdapter.openDataBase();
试一试{
String query=“选择ExecutiveCode、CaptureDate、CaptureTime、经度、纬度”+//4
“来自WMLiveGPSData”+
“其中UploadFlag='1';
ArrayList stringList=gpsAdapter.selectRecordsFromDBList(查询,空);
System.out.println(“==WMLiveGPSData==stringList==”+stringList.size());
gpsAdapter.close();
如果(stringList.size()>0){
对于(int i=0;i
}
这是我的清单文件
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MassGPSTrackingActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HomeActivity" android:screenOrientation="unspecified"></activity>
<service android:enabled="true" android:name=".service.UploadService" />
<receiver android:name="com.mass.gps.service.GpsReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action." />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<service android:enabled="true" android:name="com.mass.gps.service.UploadService" />
问题是它没有上服务课
protected void onStop(){
super.onStop();
if(gpsReceiver != null){
unregisterReceiver(gpsReceiver);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
gpsReceiver = new GpsReceiver();
IntentFilter intentFilter1 = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
intentFilter1.addAction(Intent.ACTION_BOOT_COMPLETED);
intentFilter1.addAction(Intent.ACTION_POWER_CONNECTED);
intentFilter1.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(gpsReceiver, intentFilter1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyLocationListener());
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format( "Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude());
longitude = location.getLongitude();
latitude =location.getLatitude();
//save GPS coordinate to PDA DB
GPSDBAdapter dbAdapter = GPSDBAdapter.getDBAdapterInstance(HomeActivity.this);
dbAdapter.openDataBase();
dbAdapter.insertGPS(longitude, latitude, "MASS", deserializeObject());
dbAdapter.close();
//After save GPS coordinate it upload to backend using service
startService(new Intent(HomeActivity.this, UploadService.class));
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(HomeActivity.this, "Provider status changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(HomeActivity.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(HomeActivity.this, "Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
}
请帮我解决这个问题
提前感谢。我认为您的包名不是正确的清单文件
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MassGPSTrackingActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HomeActivity" android:screenOrientation="unspecified"></activity>
<service android:enabled="true" android:name=".service.UploadService" />
<receiver android:name="com.mass.gps.service.GpsReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action." />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<service android:enabled="true" android:name="com.mass.gps.service.UploadService" />
将您的服务名称指定为packagename在接收器中使用此名称:
Intent i = new Intent();
i.setClassName("com.intelligent.locator", "com.intelligent.locator.AlarmActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
如果您选中System.out.println