Thread connection to web server lags 190-318/system_process E/ThrottleService - java

I made class extends service and I wrote a separate thread sleeps for 1 sec
My service and Thread:
public class UpdaterService extends Service {
private static String TAG = UpdaterService.class.getSimpleName();
private Updater updater;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
updater = new Updater();
updater.start();
Log.d(TAG, "Create'd");
super.onCreate();
}
#Override
public synchronized int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Start'd");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Log.d(TAG, "Destroy'd");
super.onDestroy();
}
class Updater extends Thread {
ArrayList<chatData> list = new ArrayList<chatData>();
ArrayList<String> getContactsList = new ArrayList<String>();
Boolean thereIsNewData = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String yourID = prefs.getString("KEY_USERNAME", "No login info available");
void getData(){
chatServiceHandler jsonParser = new chatServiceHandler();
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("yourID", yourID));
String json = jsonParser.makeServiceCall("http://example.com/getMSG.php", contactsServiceHandler.GET, nvp);
Log.d("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
list.clear();
JSONArray contactsArray = jsonObj.getJSONArray("MSGhandling");
for (int i = 0; i < contactsArray.length(); i++) {
JSONObject catObj = (JSONObject) contactsArray.get(i);
chatData cat = new chatData(catObj.getString("sender"), catObj.getString("receiver"),catObj.getString("msg"),catObj.getString("msgID"));
list.add(cat);
thereIsNewData = true;
}
}
} catch (JSONException e) {
e.printStackTrace();
thereIsNewData = false;
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
thereIsNewData = false;
}
}
#Override
public void run() {
while (true) {
try {
DatabaseAdapter helper = new DatabaseAdapter(UpdaterService.this);
getData();
if(thereIsNewData){
for(int i =0; i < list.size(); i++){
chatData messages = list.get(i);
Log.d(TAG, "From: "+messages.getSenderID()+" TO:"+messages.getReceiverID()+" MSG: "+messages.getMSG());
helper.storeMSG(messages.getSenderID() , messages.getReceiverID() , messages.getMSG() , messages.getMsgID());
Intent newMessage = new Intent();
newMessage.setAction("NEW_MESSAGE");
sendBroadcast(newMessage);
}
list.clear();
thereIsNewData = false;
}else{
Log.d(TAG, "There is no new data");
}
sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
}
It works fine for like 10 secs it loops for 10 times but after that it stops for like 30 secs and shows this error:
LOG_CAT:
190-318/system_process E/ThrottleService﹕ problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
03
Then the same thing happen loops for 10 secs then stops for 30 more

Related

Notification Service from JSON

How make notification?
How to check the date of the news and show notification when there is news?
Can service get SharedPref from Fragment and check and then make notification or no?
TabFragment1.class code:
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String imageUrl = object.getString("urlToImage");
String articleUrl = object.getString("url");
String newsdata = object.getString("publishedAt");
sPref = getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, newsdata);
ed.commit();
Toast.makeText(getActivity(), "Text saved", Toast.LENGTH_SHORT).show();
News news = new News(title, desc, imageUrl, articleUrl);
myAdapter.addNews(news);
myAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Notification Service code:
public class Notification extends Service {
String datanews;
String titlenotif;
String destnotif;
MyAsynk asynk;
final String SAVED_TEXT = "saved_text";
String checker;
SharedPreferences sPref;
#Override
public void onCreate() {
super.onCreate();
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 0, 1800000); //тикаем каждые 30 мinute без задержки 1800000
}
class UpdateTimeTask extends TimerTask {
public void run() {
sPref = getSharedPreferences("MyPref",MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
checker = sPref.getString(savedText, "0");
if(datanews != checker){
asynk = new MyAsynk();
asynk.execute();
createNotification(getApplicationContext());//пушим уведомление
} else {
asynk = new MyAsynk();
asynk.execute();
}
}
}
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
#Override
protected StringBuilder doInBackground(Void... voids) {
StringBuilder stringBuilder = new StringBuilder();
String key = "0aa2713d5a1a4aad9a914c9294f6a22b";
try {
URL url = new URL("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=" + key);
URLConnection uc = url.openConnection();
uc.connect();
BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
int ch;
while ((ch = in.read()) != -1) {
stringBuilder.append((char) ch);
}
} catch (Exception e) {e.printStackTrace();}
return stringBuilder;
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
}
catch (Exception e){e.printStackTrace();}
}
}
private void createNotification(Context context) {
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder ncBuilder = new NotificationCompat.Builder(context);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
ncBuilder.setVibrate(new long[]{500});
ncBuilder.setLights(Color.WHITE, 3000, 3000);
ncBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
ncBuilder.setContentIntent(pIntent);
ncBuilder.setContentTitle(titlenotif + "");
ncBuilder.setContentText(destnotif + "");
ncBuilder.setTicker("You have news!");
ncBuilder.setSmallIcon(R.drawable.news_icon);
ncBuilder.setAutoCancel(true);
manager.notify((int)System.currentTimeMillis(),ncBuilder.build());
}
public IBinder onBind(Intent arg0) {
return null;
}
}
Yes Service can read SharedPreference and can make notification.
If I understood correctly, you need to create the notification in the onPostExecute function of your MyAsynk class.
So you may try adding an public attribute in your AsyncTask like this.
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
public boolean showNotification;
// .. Other functions
}
Now in your UpdateTimerTask
if(datanews != checker){
asynk = new MyAsynk();
asynk.showNotification = true;
asynk.execute();
} else {
asynk = new MyAsynk();
asynk.showNotification = false;
asynk.execute();
}
Now in the onPostExecute of your MyAsynk class, you need to check the boolean and create the notification accordingly.
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
try {
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String title = object.getString("title");
String desc = object.getString("description");
String newsdata = object.getString("publishedAt");
datanews = newsdata;
titlenotif = title;
destnotif = desc;
}
// Create notification here on demand
if(showNotification) createNotification(getApplicationContext);
}
catch (Exception e){e.printStackTrace();}
}
Update
From comment
Maybe somehow it is necessary to check the date of the publication of
news, verify it with the current date and display a notice .. So you
need to show the notice only when there is news
If you're planning to track the new news from client side only, you might have to do a lot of coding including keeping a local storage and checking each time if a new news arrived or not. You need to have a server-side implementation here I guess. Which will send you a push notification when a new news is received. The server should handle the syncing and other mechanisms.

Android studio offline login registration

when i am doing offline login my app is crashing...and showing the error
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
In Online it is working fine no issues but in offline it is crashing not at all giving where the issue is please help me in this
public class MainActivity extends AppCompatActivity {
**// Initializing variables**
EditText login;
EditText password;
String statusRes;
String id;
String projectName;
String loginValue;
String stockPoint;
JSONObject myRespObject = null;
public static final String Passkey = "passKey";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("LOGIN");
setContentView(R.layout.login);
login = (EditText) findViewById(R.id.loginname);
password = (EditText) findViewById(R.id.Password);
final Button saveme = (Button) findViewById(R.id.save);
**SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
saveme.setOnClickListener(new Button.OnClickListener() {
public URL url;
public void onClick(android.view.View v) {
if (!CheckNetwork.isInternetAvailable(MainActivity.this){
if (!validate()) {
onLoginFailed();
return;
}
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, "");
String Passkey = prefs.getString(AppConstants.PASS_KEY, "");
String Internet = prefs.getString("Internet", "false");
String projectName = prefs.getString(AppConstants.PROJECT_NAME, "");
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),"");
String id = prefs.getString(AppConstants.ID, "");
Intent profactivity = new Intent(MainActivity.this, View.class);
profactivity.putExtra("Internet", false);
profactivity.putExtra("loginValue", loginValue);
profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", stockPoint);
startActivity(profactivity);
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show();
finish();
}
****for the above code, here it is throughing the error**
try {
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
try {
new Thread(new Runnable() {
**//Thread to stop network calls on the UI thread**
public void run() {
//Request the HTML
ArrayList<String> list = null;
try {
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue;
Log.i("httpget", "################" + ROOT_URL);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ROOT_URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String server_response = EntityUtils.toString(response.getEntity());
myRespObject = new JSONObject(server_response);
//Do something with the response
//Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show();
statusRes = myRespObject.getString("status");
JSONObject respObject = myRespObject.getJSONObject("response");
id = respObject.getString("_id");
AppConstants._ID = id;
projectName = respObject.getString("projectName");
Actors actor = new Actors();
list = new ArrayList<>();
JSONArray jsonArray = respObject.getJSONArray("stockPoint");
Intent i = getIntent();
Serializable subject = i.getSerializableExtra("stockPoint");
if (jsonArray != null) {
int len = jsonArray.length();
for (int k = 0; k < len; k++)
list.add(jsonArray.get(k).toString());
}
actor.setStockPoint(list);
AppConstants.STOCK_POINT = stockPoint;
stockPoint = respObject.getString("stockPoint");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
final ArrayList<String> finalList = list;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
statusRes = myRespObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
if (statusRes.equalsIgnoreCase("success")) {
SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(AppConstants.LOGIN_VALUE, loginValue);
editor.putString(AppConstants.PASS_KEY, passValue);
editor.putString("Internet", "true");
editor.putString(AppConstants.ID, id);
editor.putString(AppConstants.PROJECT_NAME, projectName);
editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint));
editor.commit();
**//Here move to next screen or home screen**
Intent profactivity = new Intent(MainActivity.this, View.class); profactivity.putExtra("Internet", true); profactivity.putExtra("loginValue", loginValue); profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", finalList);
startActivity(profactivity);
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show();
finish();
} else if (statusRes.equalsIgnoreCase("failed")) {
if (!validate()) {
onLoginFailed();
return;
}
}
}
});
}
}).start();
//return data;
} catch (Exception e) {
Log.i("httpget", "################Error1 -->" + e.getStackTrace());
**Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();**
}
} catch (UnsupportedEncodingException ex) {
finish();
}
}
});
}
public boolean validate() {
boolean valid = true;
String email = login.getText().toString();
String passwor = password.getText().toString();
if (email.isEmpty() || email.length() < 2 || email.length() > 10) {
login.setError("enter valid username");
valid = false;
} else {
login.setError("Invalid username");
}
if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) {
password.setError("enter valid password");
valid = false;
} else {
password.setError("Invalid password");
}
return valid;
}
public void onLoginFailed() {
**Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();**
}
}
--------------------------------------------------------------------------------
The error that you have mentioned says you have error on following line.
projectName = respObject.getString("projectName");
"responseObject" is null, hence you are getting NullPointerException.

onPostExecute() doesn't start

I have a problem with some information downloaded from a DDBB. I recieve all the information, but I can't store it on my arrays because the onPostExecute() method doesn't starts. I put my code:
RequestRocodromo.java, is the class for making the request and recieve the information, on "results" variable I have all the information, but I can't storage it on the arrays of onPostExecute():
#Override
protected JSONObject doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_url);
String results = "NO OK";
try
{
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("mac", _mac ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getAllHeaders();
response.getEntity();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(response.getEntity());
}
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject jsonResponse)
{
super.onPostExecute(jsonResponse);
List<String> values = new ArrayList<String>();
ArrayList<String> rocodromoId = new ArrayList<String>();
ArrayList<String> rocodromoArray = new ArrayList<String>();
ArrayList<String> ciudadArray = new ArrayList<String>();
ArrayList<String> comentarioArray = new ArrayList<String>();
//Procesamos los resultados
try
{
if(jsonResponse != null)
{
JSONArray jsonMainNode =jsonResponse.optJSONArray("edificios");
int lengthJsonArr =jsonMainNode.length();
for(int i=0; i<lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
rocodromoId.add(jsonChildNode.optString("id"));
rocodromoArray.add(jsonChildNode.optString("nombre"));
ciudadArray.add(jsonChildNode.optString("ciudad"));
comentarioArray.add(jsonChildNode.optString("comentario"));
values.add(jsonChildNode.optString("nombre"));
}
}
String result[] = values.toArray(new String[values.size()]);
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception e)
{
String result = "null";
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
}
Rocodromo.java, here is where I start the execute method:
RequestRocodromo re = new RequestRocodromo(ctx, finalURL + "request=1");
re.execute("");
Rocodromo.java, here is my broadcast, when I try to obtain the arraylist information I recieve a nullException, because my arraylist are null because it never starts the onPostExecute() method.
public class ReceptorBroadcast extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(RequestRocodromo.ACTION_REQUEST_ROCODROMO.equals(intent.getAction()))
{
idRocodromo = intent.getStringArrayListExtra("id_rocodromo");
Toast.makeText(getApplicationContext(), idRocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
rocodromo = intent.getStringArrayListExtra("rocodromoArray");
Toast.makeText(getApplicationContext(), rocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
ciudad = intent.getStringArrayListExtra("ciudadArray");
Toast.makeText(getApplicationContext(), ciudad.get(0).toString(), Toast.LENGTH_LONG).show();
comentario = intent.getStringArrayListExtra("comentarioArray");
Toast.makeText(getApplicationContext(), comentario.get(0).toString(), Toast.LENGTH_LONG).show();
}
}
}
Can someone help my with that? Thanks! :)
Change on doInBackGround return null to:
try {
return new JSONObject(reusults);
} catch (Throwable t) {
return null;
}
Change you broadcast receiver call in your doInBackground().. as
runOnUiThread(new Runnable() {
#Override
public void run() {
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
});
and check null result in onPostExecute as..
if(null!=jsonResponse) // avoids null pointer;

Calling a method inside thread in android

Hello below is a method where fileUpload method is called and after uploading files i want to delete the synchronized object and i did so. and now i have to reload the page by calling fillRecipients() method, what is does is it lists all the information from the database and shows in the listView. Since i have used the thread it doesnot allow me to put fillRecipeints inside the thread but i want it at line no 230[commented below as Line No 230] below
This is my Synchronize method:
public void synchronize(final String id){
dialog = ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//uploading.setText("uploading started.....");
//dialog.show();
}
});
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
//Line NO 230 here i want to add fillRecipients() method
}
dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
dialog.dismiss();
}
}
cData.close();
mDbHelper.close();
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
This is my fillRecipeints() method:
private void fillRecipients(){
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor==null){
System.out.println("empty cursor");
}
else{
String [] from = new String[]{MunchaDbAdapter.FLD_RECIPIENT_ID};
int [] to = new int[]{R.id.text1};
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this, R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}
can any body help me?
public void synchronize(final String id) {
new UploadAsync.execute();
}
//async class to do task in background and notify UI after completion of task in onPost()
class UploadAsync extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog = null;
boolean isUploaded = false;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog.show(ViewRecipients.this, "", "Uploading this file...", true);
}
#Override
protected Void doInBackground(Void... params) {
try{
mDbHelper.open();
Cursor cData = mDbHelper.fetchRecipientInfo(id);
for(cData.moveToFirst();!cData.isAfterLast();cData.moveToNext()){
String id = cData.getString(cData.getColumnIndex("fld_recipient_id"));
String info = cData.getString(cData.getColumnIndex("fld_info"));
String latitude = cData.getString(cData.getColumnIndex("fld_latitude"));
String longitude = cData.getString(cData.getColumnIndex("fld_longitude"));
ArrayList<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
try {
serverResponseCode = uploadFile(imagesArray, info, latitude, longitude, id);
if (serverResponseCode==200){
mDbHelper.deleteRecipientRecId(id);
isUploaded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
cData.close();
mDbHelper.close();
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//close dialog
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
if(isUploaded){
Toast.makeText(ViewRecipients.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
fillRecipients();
}
}
}
private void fillRecipients() {
mCursor = mDbHelper.fetchAllRecipientsInfo();
if (mCursor == null) {
System.out.println("empty cursor");
} else {
String[] from = new String[] { MunchaDbAdapter.FLD_RECIPIENT_ID };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter recipient = new SimpleCursorAdapter(this,
R.layout.recipient_show, mCursor, from, to);
setListAdapter(recipient);
}
}

Connection from Activity to Service takes too long

Im currently developing a Music Player and due to the fact that each time the orientation changes on the Phone and the Activity is re-created, I wanted the music to be played by a service. This way, the user is able to leave the activity without the music stopping..
Now.. I have this weird issue I been unable to solve... Each time I created the Activity and Inflate the GUI, the service is started. But the Service always gets Bounded after the Activity has send the data... So the music never starts... I know this happens because if I add a Button to resend the data, the Music starts playing... Here is my code for the activity:
public class Player extends Activity{
private Cursor audioCursor;
public static int position=0;
private int count;
private boolean pause = false,
play= false,
stop= false,
next= false,
back= false,
playerActive= true,
dataChanged= false,
finished= false,
playing= true;
private String action;
Messenger mService = null;
boolean mIsBound;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private ServiceConnection mConnection=null;
static final int MSG_SET_BOOLEAN_VALUE = 5;
static final int MSG_SET_STRING_VALUE = 4;
static final int MSG_SET_INT_VALUE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
Bundle extras = getIntent().getExtras();
action=extras.getString("action");
if(!(Background.isRunning()))
startService(new Intent(Player.this, Background.class));
doBindService();
if(action.equals("play")){
position=extras.getInt("position");
String[] proj = {
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.ALBUM_ID};
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Audio.Media.IS_MUSIC, null,
MediaStore.Audio.Media.TITLE + " ASC");
startManagingCursor(audioCursor);
count = audioCursor.getCount();
inflatePlayer();
/////////////////////THIS IS THE CODE THAT ACTS BEFORE THE SERVICE CONNECTION
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
}
}
//THIS CODE MUST BE FASTER, BUT THE CONNECTION TAKES TOO LONG
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
Toast.makeText(getApplicationContext(), "ATTACHED!", Toast.LENGTH_LONG).show();
try {
Message msg = Message.obtain(null, Background.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_LONG).show();
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
Toast.makeText(getApplicationContext(), "UNATTACHED!", Toast.LENGTH_LONG).show();
}
};
private void inflatePlayer(){
//LOTS OF CODE FOR THE GUI, NOTHING TO DO WITH THE SERVICE... SO I OMITTED IT
}
#Override
protected void onStop(){
playerActive=false;
try {
doUnbindService();
} catch (Throwable t) {
}
if(!playing)
stopService(new Intent(Player.this, Background.class));
super.onStop();
}
#Override
protected void onDestroy(){
playerActive=false;
audioCursor.close();
try {
doUnbindService();
} catch (Throwable t) {
}
if(!playing)
stopService(new Intent(Player.this, Background.class));
super.onDestroy();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SET_INT_VALUE:
String str = Integer.toString(msg.getData().getInt("int1"));
Toast.makeText(getApplicationContext(), "Int Message: " + str, Toast.LENGTH_LONG).show();
break;
case MSG_SET_STRING_VALUE:
String str1 = msg.getData().getString("str1");
break;
case MSG_SET_BOOLEAN_VALUE:
dataChanged=msg.getData().getBoolean("dataChanged");
finished=msg.getData().getBoolean("finished");
playing=msg.getData().getBoolean("playing");
if(!playing){
if(finished){
finished=false;
finish();
}
}
default:
super.handleMessage(msg);
}
}
}
private void sendIntToService(int intvaluetosend) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putInt("int1", intvaluetosend);
Message msg = Message.obtain(null, MSG_SET_INT_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
private void sendStringToService(String stringtosend) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putString("str1", stringtosend);
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
private void sendBoolToService(boolean booltosend, String name) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putBoolean(name, booltosend);
Message msg = Message.obtain(null, MSG_SET_BOOLEAN_VALUE);
msg.setData(b);
mService.send(msg);
} catch (RemoteException e) {
}
}
}
void doBindService() {
bindService(new Intent(this, Background.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
Toast.makeText(getApplicationContext(), "BOUND!", Toast.LENGTH_LONG).show();
}
void doUnbindService() {
if (mIsBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, Background.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}
unbindService(mConnection);
mIsBound = false;
Toast.makeText(getApplicationContext(), "UNBOUND!", Toast.LENGTH_LONG).show();
}
}
}
The Service:
public class Background extends Service {
private NotificationManager nm;
private Cursor audioCursor;
MediaPlayer mp = new MediaPlayer();
private int count;
private boolean pause = false,
play= false,
stop= false,
next= false,
back= false,
playerActive= true,
dataChanged= false,
finished= false,
playing= false;
private int position;
private String action;
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
static final int MSG_SET_BOOLEAN_VALUE = 5;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private static boolean isRunning = false;
private static final String TAG = "Background";
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_INT_VALUE:
position=msg.getData().getInt("int1");
break;
case MSG_SET_STRING_VALUE:
action=msg.getData().getString("str1");
if(action.equals("play")){
String[] proj = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.TITLE};
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Audio.Media.IS_MUSIC, null,
MediaStore.Audio.Media.TITLE + " ASC");
count = audioCursor.getCount();
audioCursor.moveToPosition(position);
int column_index = audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = audioCursor.getString(column_index);
startAudioPlayer(path);
playing=true;
if(playerActive)
sendBool(playing, "playing");
}else{
startAudioPlayer(action);
playing=true;
if(playerActive)
sendBool(playing, "playing");
}
action=null;
break;
case MSG_SET_BOOLEAN_VALUE:
pause=msg.getData().getBoolean("pause");
play=msg.getData().getBoolean("play");
stop=msg.getData().getBoolean("stop");
next=msg.getData().getBoolean("next");
back=msg.getData().getBoolean("back");
playerActive=msg.getData().getBoolean("playerActive");
if(pause){
mp.pause();
play=false;
playing=false;
sendBool(playing, "playing");
pause=false;
}
if(play){
pause=false;
mp.start();
playing=true;
sendBool(playing, "playing");
play=false;
}
default:
super.handleMessage(msg);
}
}
}
private void sendInt(int intvaluetosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putInt("int1", intvaluetosend);
Message msg = Message.obtain(null, MSG_SET_INT_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "Int not send..."+e.getMessage());
}
}
}
private void sendString(String stringtosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putString("str1", stringtosend);
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "String not send..." +e.getMessage());
}
}
}
private void sendBool(boolean booltosend, String name) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
Bundle b = new Bundle();
b.putBoolean(name, booltosend);
Message msg = Message.obtain(null, MSG_SET_BOOLEAN_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
mClients.remove(i);
Log.d(TAG, "Bool not send..." +e.getMessage());
}
}
}
#Override
public void onCreate() {
super.onCreate();
showNotification();
isRunning=true;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence text = getText(R.string.maintit);
Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Player.class), 0);
notification.setLatestEventInfo(this, getText(R.string.app_name), text, contentIntent);
nm.notify(R.string.app_name, notification);
}
#Override
public void onDestroy() {
//REMEMBER TO SAVE DATA!
if(mp.isPlaying())
mp.stop();
mp.release();
isRunning=false;
audioCursor.close();
nm.cancel(R.string.app_name);
super.onDestroy();
}
public static boolean isRunning()
{
return isRunning;
}
public void startAudioPlayer(String path){
try {
if(mp.isPlaying())
mp.reset();
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
}
mp.start();
}
}
I hope someone can help, im getting very frustrated with this! Also, Im pretty sure there is no problem with the media player, I tested it before without the service... the cursors also work properly... Thing is... Do I need to necessarily call the service from the GUI for it to play the music?? What am I doing wrong?
EDIT: The website wont allow me to answer my own question so I post the solution here:
Ok, finally found a solution!
I read that the interaction with the service is only available once the onCreate method has finished... So, I added a Timer and filled it with the methods I needed to run:
new Timer().schedule(new TimerTask(){
public void run(){
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
}
}, 1000);
AND VOILA! It works! :D Hope its useful to someone!
What you need to do is to move the code in onCreate() which is dependent on the service being available to your onServiceConnected() method in your ServiceConnection implementation:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
Toast.makeText(getApplicationContext(), "ATTACHED!", Toast.LENGTH_LONG).show();
try {
Message msg = Message.obtain(null, Background.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
sendBoolToService(playerActive, "playerActive");
sendIntToService(position);
sendStringToService(action);
} catch (RemoteException e) {
Toast.makeText(getApplicationContext(), "Connection failed!", Toast.LENGTH_LONG).show();
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
Toast.makeText(getApplicationContext(), "UNATTACHED!", Toast.LENGTH_LONG).show();
}
};
I would also look at your service implementation as I cannot understand why you are calling mService = new Messenger(service). Your IBinder instance should provide you with a mechanism for obtaining a reference to your service instance.
In my case, my issue was using android:process attribute for <service> element within Android Manifest, which is supposed to improve performance, but in reallity, maybe it does once the service is running, but it takes a very long while to reach onCreate() (and so also to reach onBind()). For me it was taking minutes. Now Apps and services run smooth and as expected.
I now this a very old question, but showing your Manifest file here makes sense.
More info:
https://developer.android.com/guide/topics/manifest/service-element

Categories