I am trying to run the application in the background but when the application starts immediately the application is closed (no error is coming).I have used asynk task in the main activity.
code:
package com.android.trace;
public class LocationStat extends Activity {
double logi;
double lat;
long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Millisecon
Location loc;
LocationManager manager;
TextView t;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new MyLocationAsyncTask().execute();
}
public void onStart() {
super.onStart();
new MyLocationAsyncTask().execute();
}
private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener {
//private Location l;
//location management variables to track and maintain user location
#Override
protected Void doInBackground(Void... arg0) {
t = (TextView) findViewById(R.id.text);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationAsyncTask());
return onLocationChanged();
}
//this method is never executed i dont know why...?
public Void onLocationChanged() {
if (manager != null) {
LocationStat l = new LocationStat();
loc = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = loc.getLatitude();
logi = loc.getLongitude();
t.setText(" Your Location :\nlongitude:" + logi + "\nlatitude: " + lat); //Log.d("Your Location", ""+latLocation);
l.webcall(logi, lat);
}
return null;
}
public void onLocationChanged(Location location) {
onLocationChanged();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
public void webcall(double logi, double lat) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("logitude", Double.toString(logi)));
nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(lat)));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/location.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(LocationStat.this, "Error in http connection " + e.toString(), Toast.LENGTH_LONG).show();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Toast.makeText(LocationStat.this, result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(LocationStat.this, "Error converting result " + e.toString(), Toast.LENGTH_LONG).show();
}
}
the code for service to intiate the activity
code:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
String tag="TestService";
#Override
public void onCreate() {
Intent dialogIntent = new Intent(this, LocationStat.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(dialogIntent);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
The broadcast receiver used for initiating the service at the start up is
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
startServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(startServiceIntent);
}
}
the manifest permissions for activity,service and broadcast receiver is as follows
<service android:enabled="true" android:name=".MyService">
<intent-filter >
<action android:name="com.android.trace.MyService"/>
</intent-filter>
</service>
<receiver android:name="com.android.trace.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name=".LocationStat"
android:label="#string/title_activity_location_stat" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Anybody experiencing the same?
Use Service instead of Activity to do background long run jobs
You can only use setText and other operations on the GUI from the main GUI thread. You are trying to do this from the background thread you have started.
You must implement the AsyncTask function onPostExecute and modify your GUI from there.
out of memory, catch LOG onDestoy() method
Have you mentioned your receiver in the android manifest file,
Add this bunch of code in your manifest file,
<receiver
android:name=".MyBroadcastReceiver" >
<intent-filter android:priority="1000">
<action />
</intent-filter>
</receiver>
Related
I have a simple application that collects locations. it works without for some minutes or hours but if I disconnect or loose Internet connection, or for disable/enable GPS 4-5 or more times, it not sends connection updates anymore. and I have to restart phone most times or kill that app and start it again (some times not works again after restart) to get locations again.
My application have a simple activity and a service for running in foreground and collection and sending them to server.
Here is my code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shetapp.ranandeg">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="mydefaultnotificationchannel" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyLocationTrackerService"
android:enabled="true"
android:exported="true" />
<service android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
This is my activity :
public class MainActivity extends AppCompatActivity {
private final String TAG = "myapp-ma";
public static final String _TAG = "myapp-ma";
public static Context context;
private WebView webViewBrowser;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: main activity created.");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.context = getApplicationContext();
loadPrefs(getApplicationContext());
getControles();
setBrowser();
startService(new Intent(this , MyLocationTrackerService.class));
}
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: main activity destroyed.");
super.onDestroy();
}
#Override
protected void onResume() {
Log.d(TAG, "onResume: main activity resumed.");
super.onResume();
loadPrefs(getApplicationContext());
startService(new Intent(this , MyLocationTrackerService.class));
}
public void loadPrefs(Context context) {
Log.d(TAG, "loadPrefs: fired!");
SharedPreferences pref = getApplicationContext().getSharedPreferences(AppConfig.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
MyLocationTrackerService.USER_TOKEN = pref.getString(AppConfig.SHARED_PREFERENCES_USER_TOKEN , "xxx");
}
protected void getControles() {
Log.d(TAG, "getControles: fired!");
webViewBrowser = (WebView) findViewById(R.id.activity_main_webViewBrowser);
WebAppInterface.wv = webViewBrowser;
}
protected void setBrowser() {
webViewBrowser.addJavascriptInterface(new WebAppInterface(this), "NativeInterface");
WebSettings webSettings = webViewBrowser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webViewBrowser.setWebViewClient(new MyWebViewClient());
webViewBrowser.setWebChromeClient(new MyWebChromeClient());
webViewBrowser.loadUrl("file:///android_asset/www/index.html");
}
#Override
public void onBackPressed() {
if(webViewBrowser.canGoBack() == true) {
webViewBrowser.goBack();
} else {
MainActivity.super.onBackPressed();
}
}
}
Location tracker service :
public class MyLocationTrackerService extends Service
{
private static final String TAG = "myapp-mlts";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1 * 60 * 1000; // MINUTES*60*1000
private static final float LOCATION_DISTANCE = 0f; // 100f;
public static String USER_TOKEN = "";
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id";
private BroadcastReceiver mRegistrationBroadcastReceiver;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.d(TAG, "onLocationChanged: location change detected , "+location.getProvider());
mLastLocation.set(location);
updateServerLocation(getApplication() , location , AppConfig.SERVER_IP , MyLocationTrackerService.USER_TOKEN);
}
#Override
public void onProviderDisabled(String provider)
{
Log.d(TAG, "LocationListener onProviderDisabled , "+provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.d(TAG, "LocationListener onProviderEnabled , "+provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.d(TAG, "LocationListener onStatusChanged , " + provider);
}
protected void updateServerLocation(Context context, final Location location , final String ip , final String userToken)
{
Log.d(TAG, "LocationListener updateServerLocation, token/server : "+userToken+"/"+ip);
if(ip.equals("")){
Log.d(TAG , "ip of server is empty string. returned.");
} else if(!isConnected()){
Log.d(TAG, "updateServerLocation: not connected!");
} else if(userToken.length() < 1){
Log.d(TAG, "updateServerLocation: userToken.length() < 1 , userToken is : "+userToken);
} else {
String url = ip + "/app/ranande/location";
StringRequest request = new StringRequest(
Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
Log.d(TAG, "onResponse: " + response);
} catch (Exception e){
Log.d(TAG, "onResponse: " + e.getMessage().toString());
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String token = userToken;
if( token.equals(null) || token.equals("") ){
Log.d(TAG , "token is empty string, returned.");
}
params.put("token", token);
params.put("latitude", String.valueOf(location.getLatitude()));
params.put("longitude", String.valueOf(location.getLongitude()));
return params;
}
};
VolleyController.getInstance(context).addToRequestQueue(request);
}
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "MyLocationTrackerService onStartCommand fired.");
startForeground();
try{
Log.d(TAG, "MyLocationTrackerService onStartCommand: token/ip are "+MyLocationTrackerService.USER_TOKEN+"/"+AppConfig.SERVER_IP);
} catch (Exception ex){
Log.d(TAG, "onStartCommand: Exception! : "+ex.toString());
}
try{
super.onStartCommand(intent, flags, startId);
} catch (Exception ex){
Log.e(TAG, "onStartCommand: Exception on calling super.onStartCommand," +ex.toString());
}
return START_STICKY;
}
#Override
public void onCreate()
{
Log.d(TAG, "MyLocationTrackerService created.");
initializeLocationManager();
try {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
//use checkSelfPermission()
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} else {
//simply use the required feature
//as the user has already granted permission to them during installation
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
}
} catch (java.lang.SecurityException ex) {
Log.d(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.d(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.d(TAG, "MyLocationTrackerService destroyed.");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.d(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
try{
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
} catch (Exception ex) {
Log.d(TAG, "initializeLocationManager: error : "+ex.toString());
}
}
public Boolean isConnected(){
ConnectivityManager connectivityManager = (ConnectivityManager)getApplicationContext().getSystemService(MainActivity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
return true;
}
return false;
}
private void startForeground() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("running ...")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.globe)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.build());
}
}
After restart phone, my application works without any issue, some times I have to kill the Application from application manager and run it again but some times I have to restart the phone.
I think maybe there is an bug with phones GPS or android OS not mine App.
IS THERE ANY ERROR IN MY CODE? or how I could change and solve this problem? Is it good idea to use fuse/google service instead?
I have a method "send()" that send values to the server and then get response 0 or 1 from the server. then i want to active a method that check if its 0 or 1 and then i want to active a method that on MainActivity that called from the service.
this is the service code
public class SendThreadCommunication extends Thread {
private final static String TAG = "SendThreadCommunication";
private final int READ_TIMEOUT = 100000;
private final int CONNECTION_TINEOUT = 100000;
private Looper myLooper;
private int mResponseCode;
private String mData = "";
private final ServerRequest req;
// private RegisterUser user;
private static String ans;
public SendThreadCommunication(ServerRequest req) {
this.req = req;
}
public String readWebData(InputStream stream) {
String line = "";
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return buffer.toString();
}
#Override
public void run() {
try {
send();
// evaluateDataAndRespondToFragment(mData);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send() throws ClientProtocolException, IOException {
OutputStream mOutputStream = null;
BufferedWriter mWriter = null;
List<NameValuePair> mParameters = req.getParameters();
URL url = null;
HttpURLConnection connection = null;
try {
Looper.prepare();
url = new URL(req.returnRequestUrl());
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TINEOUT);
connection.setRequestMethod(Params.HTTP_REQUEST_METHOD_POST);
connection.setDoOutput(true);
connection.setDoInput(true);
mOutputStream = connection.getOutputStream();
mWriter = new BufferedWriter(new OutputStreamWriter(mOutputStream, Params.UTF8));
String sparams = URLEncodedUtils.format(mParameters, Params.UTF8);
mWriter.write(sparams);
mWriter.flush();
mResponseCode = connection.getResponseCode();
if (mResponseCode > 203) {
mData = readWebData(connection.getErrorStream());
//this.req.getResponse().notGoodServerEroorr();
} else {
mData = readWebData(connection.getInputStream());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
try {
if (mOutputStream != null)
mOutputStream.close();
if (mWriter != null)
mWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.disconnect();
evaluateDataAndRespondToFragment(mData);
myLooper = Looper.myLooper();
Looper.loop();
myLooper.quit();
}
}
}
private void evaluateDataAndRespondToFragment(String mData) {
Listen lis = this.req.getResponse();
if (mData.equals("1"))
lis.good();
else
lis.notGood();
if (mData.equals("0"))
{
lis.userGcmNotRegistered();
}
}
}
this service code send to the server values and get response. the method "evaluateDataAndRespondToFragment" check if its 0 or 1 and then active the appropriate method. that method should trigger other method in the MainActivity.
i know that runOnUiThread handle this, but i dont know how to use it.
the method on the MainActivity change the UI.
this is the MainActivity code
public class MainActivity extends Activity implements SensorEventListener, Listen {
private BroadcastReceiver statusReceiver;
private IntentFilter mIntent;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
SendValues sv;
int counter3 = 0;
int counter5 = 0;
int pastTime = 0;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void good() {
Toast.makeText(getApplication(), "successful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void notGood() {
Toast.makeText(getApplication(), "UNsuccssful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void userGcmNotRegistered() {
Toast.makeText(getApplication(), "There is some problem, please register again to the App", Toast.LENGTH_LONG).show();
}
}
Here it should active one of the methods "good","not good"....
i know that runOnUiThread handle it but i dont know how to use it and where.
if anyone could tell me what to do i will appreciate.
A service doesn't have a runOnUiThread method, but you can use intent instead of.
Simply,
Add a BroadcastReceiver to your activity,
Add receiver to your AndroidManifest.xml,
Send intent from your service.
MainActivity.java
public class MainActivity extends Activity implements SensorEventListener, Listen {
private BroadcastReceiver statusReceiver;
private IntentFilter mIntent;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
SendValues sv;
int counter3 = 0;
int counter5 = 0;
int pastTime = 0;
private static final String TAG = "MainActivity";
statusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch(intent.getIntExtra("status", -1) {
case 1:
good();
break;
case 2:
notGood();
break;
default:
userGcmNotRegistered();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(statusReceiver, new IntentFilter("com.yourpackage.yourapp.GET_STATUS_INTENT");
}
#Override
public void good() {
Toast.makeText(getApplication(), "successful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void notGood() {
Toast.makeText(getApplication(), "UNsuccssful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void userGcmNotRegistered() {
Toast.makeText(getApplication(), "There is some problem, please register again to the App", Toast.LENGTH_LONG).show();
}
}
A simple AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage.yourapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourpackage.yourapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MainActivity">
<intent-filter>
<action android:name="com.yourpackage.yourapp.GET_STATUS_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
evaluateDataAndRespondToFragment method
private void evaluateDataAndRespondToFragment(String mData) {
Intent intent = new Intent("com.yourpackage.yourapp.GET_STATUS_INTENT");
intent.putExtra(status, mData);
sendBroadcast(intent);
}
}
Additionally you need to register/unregister within your activity's onResume/onPause methods.
A bit off topic; but, Beremaran's answer is correct, you can't get the main thread from a service. However, runOnUiThread is a very important concept to know and use, to avoid blocking up your main thread. Blocking your main thread will cause the system to kill your app.
Let say you have some networking tasks to do, and you know that it can take some time to do that. Therefore you start a new Thread to do the slow work.
new Thread(new Runnable() {
#Override
public void run() {
messageFromSlowStuff = doSomeSlowStuff();
};
}).start();
Now you might want to populate the UI with the new data messageFromSlowStuff, but you can't because it is only aloud from the main thread.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
myTextView.setText(messageFromSlowStuff)
}
});
If you are only updating a view as in the example above you can use View.post() an alternative to runOnUiThread.
myTextView.post(new Runnable() {
public void run() {
messageFromSlowStuff = doSomeSlowStuff();
myTextView.setText(messageFromSlowStuff);
}
});
Here's the docs regarding View.post(): "post reference"
I'm trying to implement a Server-Client communication via Push from Server to Client. Since the Client is an Android device, I'm using Google Cloud Messaging to fulfill pushing a message from server to android device. I followed this tutorial
Current status: The Client get's the Registry ID from GCM. So the client - GCM communication should be fine. The Server get's the following message while trying to push the message to gcm :
2015-01-20T23:31:24.289+0100|Information: Response Code : 200
2015-01-20T23:31:24.290+0100|Information: {"multicast_id":534481856434...,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1421793086402018%64d756d9f9fd7ecd"}]}
2015-01-20T23:31:24.296+0100|Information: com.sun.enterprise.web.connector.coyote.PECoyoteResponse$PECoyoteWriter#49...
It seems like the connection between client - gcm is working. But the gcm doesn't forward the message to my client.
My gcm project is also showing just 2 requests and over 2000 errors. I don't know that much about push notification to handle this issue, maybe somebody could help me.
Here's my code
Client MainActivity
// ... some other imports
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener {
GoogleCloudMessaging gcm;
String regid;
String PROJECT_NUMBER = pn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRegId();
}
public void getRegId() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
regid = gcm.register(PROJECT_NUMBER);
msg = "Device registered, registration ID = " + regid;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
msg = "Error: " + e.getMessage();
}
Log.d("Systemablauf", "MainActivity getRegId() " + msg);
return msg;
}
}.execute(null, null, null);
}
}
Client MessageHandler
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GcmMessageHandler extends IntentService {
String msg;
private Handler handler;
public GcmMessageHandler(String name) {
super("GcmMessageHandler");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate() {
super.onCreate();
handler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
msg = extras.getString("title");
showToast();
Log.d("Systemablauf", "Received: (" + messageType + ") " + extras.getString("title"));
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void showToast() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
}
Client BroadcastReceiver
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Explicitly specify that GcmMessageHandler will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GcmMessageHandler.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
Log.d("Systemablauf", "onReceive()");
}
}
Client Manifest
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xml>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thesis.com.example.clientsync"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission
android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.VIBRATE"/>
<uses-permission
android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission
android:name="android.permission.WAKE_LOCK"/>
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE"/>
<permission
android:name="thesis.com.example.clientsync.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission
android:name="thesis.com.example.clientsync.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.RECEIVE" />
<category
android:name="thesis.com.example.clientsync" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service
android:name="service.MainService" />
</application>
</manifest>
Server Servlet
#WebServlet("/ServerServlet")
public class ServerServlet extends HttpServlet {
public ServerServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
sendNotification();
}
private void sendNotification() {
System.out.println("Sending POST to GCM");
String apiKey = "AIzaSyA0pOZf13cZzqQHrWBZfFE9XFMHA5ftiAo";
Content content = createContent();
POST2GCM.post(apiKey, content);
}
private static Content createContent() {
// TODO Auto-generated method stub
Content c = new Content();
c.addRegId("APA91bFrSX_mGLzLUf2Va6...");
c.createData("Test Title", "Test Message");
return c;
}
}
Server Post
public class POST2GCM {
public static void post(String apiKex, Content content) {
String apiKey = "AIzaSyA0pO...";
try {
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "key = " + apiKey);
connection.setDoOutput(true);
Gson gsonMapper = new GsonBuilder().create();
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(gsonMapper.toJson(content));
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL: " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
System.out.println(response.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Server Content
#SuppressWarnings("serial")
public class Content implements Serializable {
private List<String> registration_ids;
private Map<String, String> data;
public void addRegId (String regId) {
if (registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData (String title, String message) {
if (data == null)
data = new HashMap<String, String>();
data.put("title", title);
data.put("message", message);
}
}
I already have this application that once the user clicks a button, the main activity calls a Broadcast Receiver that in turn calls a Service which sends the GPS Location of the user to an EMail Address in a certain interval. The app works just fine.
However, what I want to do is that when the user activates the Power Button of the device, the Broadcast Receiver will activate. So far, I've seen this question and I've used it so my manifest file looks something like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.angelo.serviceexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.angelo.serviceexample.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.permission.PREVENT_POWER_KEY" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.angelo.serviceexample.GPSLoggerService" />
<receiver android:name="com.angelo.serviceexample.AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"> </action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</receiver>
</application>
</manifest>
And the Broadcast Receiver class has intent-filters to call it when activated.
The AlarmReceiver.java file looks like this so far:
package com.angelo.serviceexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,GPSLoggerService.class));
//Toast.makeText(, "power button clicked",Toast.LENGTH_LONG).show();
Log.v("Tag", "AlarmReceiver called.");
}
}
However, when I was checking LogCat, the Log only activates whenever the user presses the button in the Main Activity as shown here:
public class MainActivity extends Activity {
private int currentIntervalChoice = 0;
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
setAppInfo();
addButtonListeners();
enableControls();
return true;
}
return super.dispatchKeyEvent(event);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAppInfo();
addButtonListeners();
enableControls();
}
private void setAppInfo() {
TextView txtInfo = (TextView)findViewById(R.id.app_info);
txtInfo.setText(Html.fromHtml(getString(R.string.app_info)));
Linkify.addLinks(txtInfo, Linkify.ALL);
}
private void addButtonListeners() {
((Button)findViewById(R.id.start_logging)).setOnClickListener(btnClick);
((Button)findViewById(R.id.logging_interval)).setOnClickListener(btnClick);
}
private void enableControls(){
boolean isServiceRunning = AppSettings.getServiceRunning(this);
String buttonText = getString(R.string.start_logging);
if(isServiceRunning){
buttonText = getString(R.string.stop_logging);
((Button)findViewById(R.id.logging_interval)).setEnabled(false);
}
else{
((Button)findViewById(R.id.logging_interval)).setEnabled(true);
}
((Button)findViewById(R.id.start_logging)).setText(buttonText);
}
private void changeLoggingIntercal(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String loggingIntervals[] = { "1 minute", "3 minute", "5 minutes", "10 minutes" };
builder.setTitle(getString(R.string.logging_interval));
builder.setSingleChoiceItems(loggingIntervals, currentIntervalChoice, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
currentIntervalChoice = which;
setLoggingInterval(currentIntervalChoice);
dialog.dismiss();
}
});
builder.show();
}
private void setLoggingInterval(int intervalChoice){
int interval = 1;
switch(intervalChoice){
case 0: interval = 1; break;
case 1: interval = 3; break;
case 2: interval = 5; break;
case 3: interval = 10; break;
default: interval = 1; break;
}
AppSettings.setLoggingInterval(this, interval);
}
public void setLogFileName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(new Date());
String filename = "GPSLog." + dateString + ".kml";
AppSettings.setLogFileName(this, filename);
}
private View.OnClickListener btnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_logging:{
toggleLogging(AppSettings.getServiceRunning(MainActivity.this),
AppSettings.getLoggingInterval(MainActivity.this));
enableControls();
break;
}
case R.id.logging_interval:{
changeLoggingIntercal();
break;
}
}
}
};
private void toggleLogging(boolean isStart, int interval){
AlarmManager manager = (AlarmManager)getSystemService(Service.ALARM_SERVICE);
PendingIntent loggerIntent = PendingIntent.getBroadcast(this, 0,new Intent(this,AlarmReceiver.class), 0);
if(isStart){
manager.cancel(loggerIntent);
AppSettings.setServiceRunning(this, false);
AppLog.logString("Service Stopped.");
}
else{
setLogFileName();
long duration = interval * 60 * 1000;
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), duration, loggerIntent);
AppSettings.setServiceRunning(this, true);
Toast.makeText(getApplicationContext(), "Service Started with interval " + interval
+ ", Logfile name: " + AppSettings.getLogFileName(this), Toast.LENGTH_LONG).show();
AppLog.logString("Service Started with interval " + interval
+ ", Logfile name: " + AppSettings.getLogFileName(this));
}
}
}
Also, this is the Service Class that is in question:
public class GPSLoggerService extends Service implements LocationListener{
private static final int gpsMinTime = 500;
private static final int gpsMinDistance = 0;
private static final int TIMER_DELAY = 1000;
private LocationManager manager = null;
private double latitude = 0.0;
private double longitude = 0.0;
private Timer monitoringTimer = null;
public GPSLoggerService() {
AppLog.logString("GPSLoggerService.GPSLoggerService().");
}
#Override
public IBinder onBind(Intent arg0) {
AppLog.logString("GPSLoggerService.onBind().");
return null;
}
#Override
public void onCreate() {
AppLog.logString("GPSLoggerService.onCreate().");
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
AppLog.logString("GPSLoggerService.onStartCommand().");
startLoggingService();
startMonitoringTimer();
return Service.START_STICKY;
}
#Override
public void onLocationChanged(Location location) {
AppLog.logString("GPSLoggerService.onLocationChanged().");
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderDisabled().");
}
#Override
public void onProviderEnabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderEnabled().");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
AppLog.logString("GPSLoggerService.onStatusChanged().");
}
private void startLoggingService(){
if (manager == null){
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = manager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0){
manager.requestLocationUpdates(bestProvider, gpsMinTime,gpsMinDistance, this);
}
else{
final List<String> providers = manager.getProviders(true);
for (final String provider : providers){
manager.requestLocationUpdates(provider, gpsMinTime, gpsMinDistance, this);
}
}
}
private void stopLoggingService(){
stopSelf();
}
private void startMonitoringTimer(){
monitoringTimer = new Timer();
monitoringTimer.scheduleAtFixedRate(
new TimerTask(){
#Override
public void run(){
if (longitude != 0.0 && latitude != 0.0){
monitoringTimer.cancel();
monitoringTimer = null;
manager.removeUpdates(GPSLoggerService.this);
sendCoordinates(latitude, longitude);
stopLoggingService();
}
}
},
GPSLoggerService.TIMER_DELAY,
GPSLoggerService.TIMER_DELAY);
}
private void sendCoordinates(double latitude, double longitude){
Looper.prepare();
GMailSender sender = new GMailSender("sender#gmail.com", "password");
//Subject, Body, Sender, Recipient
try {
sender.sendMail("Sample GPS Location",
"This should go to my yahoo account. My Location is at is - Lat: " + latitude + " Long: " + longitude,
"sender#gmail.com",
"receiver#yahoo.com");
Toast.makeText(getApplicationContext(), "Mail Sent", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
So far, I'm reading online on how to call a Broadcast Receiver through a phone event which in turn, calls the Service. I think I'm having problems because of the bind override I set though I'm not sure.
u have to start the services
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service=new Intent(context,UploadObservationService.class);
**context.startService(service);**
Log.v("Tag", "AlarmReceiver called.");
}
}
I have GPS Tracking application main goal is saving GPS coordinate to backed database every 5 minutes interval. So i created Service & receiver because even my my application doesn't open / run this should work.
After user enter executive code , it create database and go to welcome screen.
In there it start GPS capturing & save it to PDA database calling service to upload. I have receiver, when phone isBooted it start this receiver & receiver call service.
My problem is receiver doesn't call service. It didn't go to Service class.
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();
}
}
This is my receiver .
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);
}
}
}
This is my service.
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();
}
};
}
This is my manifest file
<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" />
Issue is it didn't go to Service class.
Please help me out this question...
Thanks in advance..
i think u r package name is not correct manifest file
<service android:enabled="true" android:name="com.mass.gps.service.UploadService" />
specify your service name as packagename
Use this in the receiver:
Intent i = new Intent();
i.setClassName("com.intelligent.locator", "com.intelligent.locator.AlarmActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);