I have created an Intent Service and I am calling it from NotificationChecker.java which extends Broadcast receiver.What I want to do is in background at a fixed interval of time I want to download text from a URL and toast that string.In intent service I am reading data from the URL but It is not receiving any data.Here is my Sample Code.
package com.jamiahamdard.hammad.noticeboard;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MyIntentService extends IntentService {
String finalJson="ygf";
private Handler handler;
Context context;
public MyIntentService() {
super("MyIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url=new URL("http://sig.ieeejamiahamdard.org/notice_board/notices.txt");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
finalJson = buffer.toString();
Toast.makeText(getApplicationContext(), finalJson,Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
}
and for Broadcast Receiver
package com.jamiahamdard.hammad.noticeboard;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NotificationChecker extends BroadcastReceiver {
SharedPreferences student;
String finalJson;
Context mycontext;
Intent intent;
public NotificationChecker() {
}
#Override
public void onReceive(Context context, Intent intent) {
String studentData=intent.getExtras().getString("student");
context.startService(new Intent(context,MyIntentService.class));
}
}
Related
I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format. Despite everything my AsyncTask doesn't seem to actually be executing. Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code. Hoping someone can help! Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CatImages req = new CatImages();
req.execute();
}
class CatImages extends AsyncTask<String, Integer, String> {
ArrayList<String> ids = new ArrayList<String>();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
ids.add(id);
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String fromDoInBackground) {
super.onPostExecute(fromDoInBackground);
}
}
}
Try changing !=null to ==null in your second while loop.
Also you just need while(on) in your first while loop.
Let me know if anything changes.
I try to develop an app in java,
I try to get all clipboard statement whatever inside the app or when the app closed (home button pressed )
I tried a lot of things after searching on the internet but I don't get anything excepted this problem happen with SDK >= 26
------------ steps I do ----------
create service
define service in the manifest file
create a notification channel
start service by (startForeground)
NOTE: THIS WORKING VERY WELL IF I COPY INSIDE APP
----------------------------------------- ClipboardMonitorService.java
package com.example.testclipboard;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Date;
/**
* Monitors the {#link ClipboardManager} for changes and logs the text to a file.
*/
public class ClipboardMonitorService extends Service {
private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
//startForeground();
// TODO: Show an ongoing notification when this service is running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
//mHistoryFile = new File(Environment.getExternalStorageDirectory(), FILENAME);
mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
Log.i("Service Created ","Yes Created !");
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.testclipboard";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
//.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
String _string =mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
logger(_string);
ClipData clip = mClipboardManager.getPrimaryClip();
mThreadPool.execute(new WriteHistoryRunnable(
clip.getItemAt(0).getText()));
}
};
private void logger(String txt){
Log.i("Logger : " , txt);
}
private class WriteHistoryRunnable implements Runnable {
private final CharSequence mTextToWrite;
public WriteHistoryRunnable(CharSequence text) {
mTextToWrite = text;
}
#Override
public void run() {
if (TextUtils.isEmpty(mTextToWrite)) {
// Don't write empty text to the file
return;
}
Log.i("Copyed : ",mTextToWrite.toString() );
String clipboared = mTextToWrite.toString();
//writer.newLine();
//writer.close();
}
}
}
--------------------------------------- MainActivity.java
package com.example.testclipboard;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.hbb20.CountryCodePicker;
public class MainActivity extends AppCompatActivity {
private Intent forService;
ClipboardManager myClipBoard ;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forService = new Intent(MainActivity.this,TestSmallService.class);
btnClick = (Button)findViewById(R.id.btntest);
btnClick.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
Log.i("Btn Clicked ","Heyys");
// ToDO : The Old One
Intent intent = new Intent(getBaseContext(), ClipboardMonitorService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getBaseContext().startForegroundService(intent);
} else {
getBaseContext().startService(intent);
}
}
});
}
}```
I am trying to send an email with the attachment of a file from the external storage. However I can not see the file or send it due to and IO error from both the emulator and phone.
Here is my code:
package com.energyengineeringltd.www.energyengineeringltd;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
public class emailone extends Activity {
private String filepath = "MyFileStorage";
File myExternalFile;
String myData = "";
Button b1;
EditText ed1;
String file_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
b1 = (Button) findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
b1.setEnabled(false);
} else {
Intent intent = getIntent();
String a = intent.getStringExtra("project");
String c = intent.getStringExtra("unique");
file_name = a + "1CableSupportContainmentChecklist" + c + ".txt";
myExternalFile = new File(getExternalFilesDir(filepath), file_name);
}
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ed1.getText().toString().contains("#")) {
Toast.makeText(getApplicationContext(),
"Please enter a valid email", Toast.LENGTH_SHORT).show();
} else {
File filelocation = new File(getFilesDir().getAbsolutePath() + filepath, file_name);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {ed1.getText().toString()};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
Toast.makeText(getApplicationContext(),
"sending...", Toast.LENGTH_SHORT).show();
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
}
});
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
Does anyone know what I can do to get around this IO error, it doesn't even appear in Android monitor so I have no clue. All thanks in advance!!!
I dont understand why the heck this happens?
Anyone has an idea ?
I am trying to send & recieve data from PHP n dynamically append data in xml layout.
Anyone has any idea? The stuff was working well when i just sent the data to PHP using asynctask.
But when i try to recieve and append this logcat gave me heck.
ActivityMain.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.renderscript.Element;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
#SuppressLint("NewApi") #TargetApi(Build.VERSION_CODES.GINGERBREAD) #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
public void showChatList(JSONArray json){
/*
Document doc;
String fileloc = "C:\\Users\\Admin\\workspace\\myWeb\\res\\layout\\activity_main.xml";
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(fileloc));
//Node nR = doc.getElementById("mainR");
removeChilds(nR);
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainR);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
LinearLayout LL = new LinearLayout(this);
ImageView pp = new ImageView(this);
TextView name = new TextView(this);
TextView username = new TextView(this);
int generatedId = generateViewId();
pp.setId(generatedId);
LL.setOrientation(LinearLayout.HORIZONTAL);
new ImageLoadTask(pp).execute("http://117.99.55.83/"+c.getString("img"));
name.setText(c.getString("name"));
username.setText(c.getString("username"));
LL.addView(pp);
LL.addView(name);
LL.addView(username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void removeChilds(Node node) {
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
}
public static int generateViewId() {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
}
toPHP
package com.example.myweb;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
public class toPHP extends AsyncTask<Object, Object, JSONArray>{
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
private JSONParser jsonParser = new JSONParser();
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
TextView textV1 = (TextView)main.findViewById(R.id.textV1);
ProgressBar spinner = (ProgressBar)main.findViewById(R.id.spinner);
spinner.setVisibility(View.VISIBLE);
textV1.setText("Reaching em!!");
}
#Override
protected JSONArray doInBackground(Object... v) {
//main = (MainActivity)parameters[0];
//main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
JSONArray json = null;
json = getUserLoggedIn(email, password);
//main.afterEffect("drawing");
return json;
}
public JSONArray getUserLoggedIn(String email,String password){
JSONArray json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://117.99.55.83/resource/android/CHATS.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONArray json) {
main.showChatList(json);
}
}
LOGCAT
12-30 17:47:34.418: I/Choreographer(736): Skipped 41 frames! The application may be doing too much work on its main thread.
12-30 17:47:37.221: D/dalvikvm(736): GC_CONCURRENT freed 272K, 13% free 2757K/3168K, paused 77ms+79ms, total 303ms
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i need to read the text from textview1 but the text is always not the same as "-shutdown"
but on the textview is displayed the text "-shutdown"
Or is there any other ways to read directly text from bo.toString() withut write it in a textview??
Thanks.
My activity class:
package com.example.androrem;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ReadSMS extends Activity {
private static final int duration = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_sms);
doButton1();
}
private void readData(){
new Thread() {
#Override
public void run() {
String path ="http://androidremoter.altervista.org/zero/test.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(bo.toString()); //the textview display "-shutdown"
String input = text.getText().toString();//get text from textview
String com1 = "-shutdown";
if(input==com1)//always show not work
{
TextView text2 = (TextView) findViewById(R.id.textView2);
text2.setText("work");
}
else
{
TextView text2 = (TextView) findViewById(R.id.textView2);
text2.setText("not work");
}
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void doButton1()
{
Button gettext = (Button) findViewById(R.id.test1);
gettext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
readData();
}
});
}
You can't compare two Strings like that. You are comparing the objects rather than the contents. Do this instead:
if (input.trim().equals(com1)) {
...