Recognizing the User's Current Activity in Android - android

i am working with Recognizing the User's Current Activity from http://developer.android.com/training/location/activity-recognition.html
i used folow code to create new ActivityRecognitionClient:
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private ActivityRecognitionClient mActivityRecognitionClient ;
private PendingIntent mPendingIntent ;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// code detetc user acitivity here
getActivityRecognitionClient().requestActivityUpdates((2 * 60 * 1000), createPendingRequest());
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
mActivityRecognitionClient = null;
mPendingIntent.cancel();
mPendingIntent = null;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try{
connectionResult.startResolutionForResult((Activity) this.getApplicationContext(), 0);
} catch (IntentSender.SendIntentException e) {
// it happens if the resolution intent has been canceled,
// or is no longer able to execute the request.e
e.printStackTrace();
}
} else {
// Google Play services has no idea how to fix the issue
// it rarely happens for the location service
}
}
public void startTrack() {
try {
if (!getActivityRecognitionClient().isConnected() || !getActivityRecognitionClient().isConnecting() ) {
Log.v(TAG, "getActivityRecognitionClient is not connected");
getActivityRecognitionClient().connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mPendingIntent;
}
/**
* check googleplayservices is avaible or not
*
* #return true if is avaible flase if not
*/
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mIsRemove = false;
}
private ActivityRecognitionClient getActivityRecognitionClient() {
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient = new ActivityRecognitionClient(getApplicationContext(), this, this);
}
return mActivityRecognitionClient;
}
So with it every 2 min User's Current Activity will be send to service four. in my service four(Intent service) :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
//
if (result != null) {
//
Log.d("Aha", "he he");
} else {
Log.d("Ohno", "T_T");
}
}
It work fine but when i uninstall app. and install again all ActivityRecognitionResult in servicefour is null it just can be work fine again if i restart device. I don't know how to fix this . Please help me and thanks for reading.

Here is your problem:
E/GooglePlayServicesUtil(18189): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
Your GooglePlayServices are not working.
Make sure you included them properly (post your Gradle files etc).

I will post my code for Recognizing the User's Current Activity but with newest api .
public class GPSLocationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener {
private String TAG = "[ServiceDetect]";
//
private PendingIntent mActivityRecognitionPendingIntent;
// Stores the current instantiation of the activity recognition client
private GoogleApiClient mApiClient;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (checkGooglePlayAvaible()) {
startTrack();
}
return START_STICKY;
}
#Override
public void onConnected(Bundle bundle) {
// TODO Auto-generated method stub
// -------------------------------------
// to remove ActivityRecognition call
// ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates
//----------------------------
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 2 * 60 * 1000,
createPendingRequest());
//
mApiClient.disconnect();
stopSelf();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionFailed");
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
Log.d(TAG, "onConnectionSuspended");
mApiClient.connect();
}
public void startTrack() {
if (mApiClient == null) {
mApiClient = new GoogleApiClient.Builder(getApplicationContext()).addApi(ActivityRecognition.API)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
if (!mApiClient.isConnected() || !mApiClient.isConnecting()) {
mApiClient.connect();
}
}
public PendingIntent createPendingRequest() {
if (null != mActivityRecognitionPendingIntent) {
} else {
Intent intent = new Intent(getApplicationContext(), ServiceFour.class);
mActivityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
return mActivityRecognitionPendingIntent;
}
public boolean checkGooglePlayAvaible() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
return true;
}
return false;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
And now in my servicefour . I receive ActivityRecognitionResult :
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if (ActivityRecognitionResult.hasResult(intent)) {
if (bundle.containsKey("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT")) {
String activityRecognitionResult = bundle
.getParcelable("com.google.android.location.internal.EXTRA_ACTIVITY_RESULT") + "";
Log.d(TAG, "activityRecognitionResult " + activityRecognitionResult +" (^.,,.^)");
}
}

Related

AsyncTask not called in service

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

How to add and remove multiple proximity alerts in location manager

I am trying to add multiple proximity alert in location listener by giving unique requesCode to its pendingIntent but I am unable to get the alert where I set the location. And app is also crashed several times, please help
here's my code
public class LocationTrackerService extends Service implements LocationListener {
private static final long RADIUS = 1000; // in Meters
private static final long PROX_ALERT_EXPIRATION_TIME = -1;
Context context;
String msg;
LocationManager locationManager;
public final int MINIMUM_UPDATE_DISTANCE = 100;// in meters
public final int MINIMUM_UPDATE_INTERVAL = 30 * 1000;// in seconds
public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
LocationAlertReceiver proximityAlertReceiver;
private static final NumberFormat nf = new DecimalFormat("##.########");
IntentFilter filter;
ArrayList<LocationModel> locationdata;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
context = getApplicationContext();
getPickuppoints();
registerIntents();
//will register receiver
registerReceiver();
Log.d("TAG", "service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void registerIntents() {
if (locationdata!=null && locationdata.size()>0) {
// TODO Auto-generated method stub
for (int j = 0; j < locationdata.size(); j++) {
LocationModel obj = locationdata.get(j);
setProximityAlert(obj);
}
}
}
private void getPickuppoints(){
Cursor cur=null;
Dbhelper db=new Dbhelper(context);
SQLiteDatabase sqldb=db.getReadableDatabase();
try {
String query="select * from "+Dbhelper.TBL_LATLONG;
cur=sqldb.rawQuery(query, null);
if(cur.getCount()>0){
locationdata=new ArrayList<LocationModel>();
for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
locationdata.add(
new LocationModel(
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUPID)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_PICKUP_NAME)),
cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LATTITUDE)),
cur.getDouble(cur.getColumnIndex(Dbhelper.COL_LATLONG_LONGITUDE)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTEID)),
cur.getString(cur.getColumnIndex(Dbhelper.COL_LATLONG_ROUTENUMBER))));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cur.close();
db.close();
sqldb.close();
}
#Override
public void onLocationChanged(Location location) {
try {
if (locationManager!=null) {
// TODO Auto-generated method stub
String latt = nf.format(location.getLatitude());
String longi= nf.format(location.getLongitude());
Toast.makeText(context, latt+" : "+longi, Toast.LENGTH_LONG).show();
Log.d("TAG", "latlong details" + latt+" : "+longi);
/*Location pointLocation = new Location("POINT_LOCATION");
pointLocation.setLatitude(latlongsFixed.get(index));
pointLocation.setLongitude(77.36438);
float distance = location.distanceTo(pointLocation);
Log.d("TAG", "" + distance);*/
// Toast.makeText(context,"you are meters away from your point of interest.",
// Toast.LENGTH_LONG).show();
Singelton.getInstance().setLastKnownLocation(location);
if (Utilities.checkInternetConnection(getApplicationContext())) {
if (Singelton.getInstance().getRouteNumber() != null)
sendLongLat(latt,longi);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Exception in onLocationChanged()", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(locationManager!=null)
locationManager.removeUpdates(this);
unregisterReceiver(proximityAlertReceiver);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public void sendLongLat(final String latti, final String longi) {
new AsyncTask<String, Void, String>() {
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String msg = null;
try {
JSONObject json = new JSONObject(result);
String status = json.getString("STATUS");
if (status.equalsIgnoreCase("ok")) {
msg = "Location sent";
} else {
msg = "Something went wrong";
}
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> lines = new ArrayList<String>();
Connection db = new Connection();
String routeId = Singelton.getInstance().getRouteId();
if (Utilities.checkInternetConnection(getApplicationContext())) {
try {
lines = db.putLatLong("putLatLong", "2"// route id
, longi, latti);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return lines.get(0);
}
}.execute();
}
private void setProximityAlert(LocationModel obj) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("GPS not enabled"); // GPS not found
builder.setMessage("Please switch on the GPS of your device"); // Want to enable?
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
context.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("OK", null);
builder.create().show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_UPDATE_INTERVAL, MINIMUM_UPDATE_DISTANCE, this);
Intent intent = new Intent(PROX_ALERT_INTENT+"."+obj.getPickupId());//
intent.putExtra("LOCATION", obj);
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, Integer.parseInt(obj.getPickupId())// unique id/request code
, intent, PendingIntent.FLAG_CANCEL_CURRENT);
locationManager.addProximityAlert(
obj.getLat(), // the latitude of the central point of the alert region
obj.getLongi(), // the longitude of the central point of the alert region
RADIUS, // the radius of the central point of the alert region, in meters
PROX_ALERT_EXPIRATION_TIME, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
);
filter = new IntentFilter(PROX_ALERT_INTENT);
}
private void registerReceiver()
{
proximityAlertReceiver=new LocationAlertReceiver();
registerReceiver(proximityAlertReceiver, filter);
}
}
And Proximity Alert receiver
public class LocationAlertReceiver extends BroadcastReceiver{
private int NOTIFICATION_ID=1000;
public static String PROX_ALERT_INTENT = "com.ginormous.transportmanagement.ProximityAlert";
private String uniqueid="";
LocationModel locaObj;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub\
this.context=context;
try {
LocationModel model=((LocationModel) intent.getSerializableExtra("LOCATION"));
Toast.makeText(context, "Proxmity alert receiver; id : "+model.getPickupId(),
Toast.LENGTH_SHORT).show();
removeProximityAlert(context, PROX_ALERT_INTENT+"."+model.getPickupId());
Toast.makeText(context, "proxmity removed", 1).show();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(context, "exception in Proxmity alert receiver",
Toast.LENGTH_SHORT).show();
}
/*if(intent.getExtras().getSerializable("LOCATION")!=null){
locaObj=(LocationModel) intent.getExtras().getSerializable("LOCATION");
}
String KEY=LocationManager.KEY_PROXIMITY_ENTERING;
Boolean isEntering=intent.getBooleanExtra(KEY, false);
if(isEntering){
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent2 = new Intent(context, MainLogin.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!",
"Location : "+locaObj.getPickupName()+",", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
Log.d(getClass().getSimpleName(), "entering");
removeProximityAlert(context,locaObj.getPickupId());
//this will send the details to server
if(Utilities.checkInternetConnection(context))
new SendArrivalDetails().execute(locaObj.getPickupId());
else
Utilities.sendArrivalDetails(context, locaObj.getPickupId(),"N");
}
else
Log.d(getClass().getSimpleName(), "exiting");
*/
}
private void removeProximityAlert(Context context,String uniqueid2) {
// TODO Auto-generated method stub
try {
LocationManager locationManager=(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Intent intent=new Intent(PROX_ALERT_INTENT+"."+uniqueid2);
PendingIntent pendingIntent=PendingIntent.getBroadcast(context, Integer.parseInt(uniqueid2), intent, 0);
locationManager.removeProximityAlert(pendingIntent);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(context, "error in removing promity alert for "+uniqueid2, Toast.LENGTH_SHORT).show();
}
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher_transport;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
public class SendArrivalDetails extends AsyncTask<String, Void, String> {
String pickupid="";
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> lines=new ArrayList<String>();
pickupid=params[0];
try {
Connection db=new Connection();
Calendar cal=Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
db.saveArrivalDetails("savepickuptimer", pickupid, Singelton.getInstance().getAttType(),sdf.format(cal.getTime()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lines.get(0);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jsonObject=new JSONObject(result);
String response=jsonObject.getString("STATUS");
if(response.equals("STATUS")){
Utilities.sendArrivalDetails(context, pickupid,"U");
Toast.makeText(context, "proximity arrival details sent", 1).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, "error sending proximity arrival details", 1).show();
}
}
}
}
And permission in Menifest file are
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
You have to save all proximity region IDs(request code) and when u want to remove these region just call to remove from locationmanager . For e.g.
Intent intent = new Intent();
intent.setAction(AppConstants.BROAD_ACTION);
for(int i=0;i<countRegionIDArr.size();i++){
PendingIntent pendingIntent = PendingIntent.getBroadcast(AlertService.this, countRegionIDArr.get(i), intent, 0);
mlocManager.removeProximityAlert(pendingIntent);
}

InstantiationException occur while Downloading using Service

I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService

how to call method in service from other activity

I have problem how to call my method in a service, my method is getambil_jmlgangguan().
Detailed code is here :
public class GetCountDataGangguanService extends Service {
public String JUMLAH_GANGGUAN ="";
public static final String TAG = "MyServiceTag1";
GlobalKoneksi konek_url = new GlobalKoneksi();
GetJmlGangguanFunction jmlGangguanFUnctions = new GetJmlGangguanFunction();
private static String KEY_SUCCESS = "success";
private static String KEY_JUMLAH_DATA = "jumlah";
JSONArray jml_data_json = null;
// UserFunctions userFunctions;
UserFunctions userFunctions = new UserFunctions();
SessionManager session;
#Override
public void onCreate() {
// TODO Auto-generated method stub
mHandlers = new ArrayList<Handler>();
Toast.makeText(this, "GetCountDataGangguan.onCreate()",
Toast.LENGTH_SHORT).show();
//getambil_jmlgangguan();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onBind()", Toast.LENGTH_SHORT)
.show();
return messenger.getBinder();
}
public class LocalBinder extends Binder {
public GetCountDataGangguanService getServerInstance() {
return GetCountDataGangguanService.this;
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d("GetCountDataGangguan.onDestroy()", "Sudah di destroy");
Toast.makeText(this, "GetCountDataGangguan.onDestroy()",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onUnbind()",
Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
public String getambil_jmlgangguan(){
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String unit_id = user.get(SessionManager.KEY_UNITID);
String regu_id = user.get(SessionManager.KEY_REGUID);
JSONObject jsondatagangguan = jmlGangguanFUnctions.getcountdata(
regu_id, unit_id);
try {
Log.d("JUMLAH_GANGGUAN",jsondatagangguan.getString(KEY_JUMLAH_DATA));
JUMLAH_GANGGUAN = jsondatagangguan.getString(KEY_JUMLAH_DATA);
} catch (JSONException e) {
e.printStackTrace();
}
return JUMLAH_GANGGUAN;
}
}
How do I call method getambil_jmlgangguan() in another activity e.g MainActivity and get result of JUMLAH_GANGGUAN periodically.

How to create widget for start and stop voice recording

In my project I have created a widget class, a service and a remote service, however I'm not able to
call the methods for starting or stopping it. I've sample codes here
For widget
Intent intent = new Intent(context, med_service.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
views.setOnClickPendingIntent(R.id.button1, pi);
Toast.makeText(context, pi.toString() + intent.toString(), Toast.LENGTH_SHORT).show();
for remote service
public class service extends Service implements IBinder{
public IBinder onBind(Intent intent) {
Log.i("RemoteService", "onBind() called");
return new RemoteServiceImpl();
}
/**
* The IRemoteInterface is defined through IDL
*/
public class RemoteServiceImpl extends IRemoteService.Stub {
#Override
public void start() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside start method", Toast.LENGTH_SHORT).show();
}
#Override
public void stop() throws RemoteException {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "inside stop method", Toast.LENGTH_SHORT).show();
}
}
for service
public class med_service extends Service{
IRemoteService mService;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("RemoteService", "onBind() called");
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
return new service();
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder service ) {
mService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
try{
RemoteServiceConnection mConnection = new RemoteServiceConnection();
getApplicationContext().bindService(new Intent(IRemoteService.class.getName()), mConnection, Context.BIND_AUTO_CREATE);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "service not bind to connection", Toast.LENGTH_SHORT).show();
}
try {
mService.start();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;
}
any kind of help is appreciated
Thank You in advance
use getService instead of getActivity

Categories

Resources