I am trying to make app where I am making server req and getting response, while I am getting response I showed it with notification even if apps killed. So this is why I made all this in service and after getting response I broadcast info got from server response to broadcastreceiver in activity to show info in a recyclerview.info showing while in apps on(no click on notification but continuous network req and response) as i made direct broadcast but while I click on notification nothing showing in recyclerview. how to solve this ..
NotificationActivity:
public class NotificationActivity extends AppCompatActivity {
GetPostAsyncTask backgroundTask;
ArrayList<NotificationDataClass> list;
NotificationListShowAdapter notificationListShowAdapter;
RecyclerView recyclerView;
Context contextNotificationActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
Intent intent=new Intent(NotificationActivity.this,ServiceClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
contextNotificationActivity=NotificationActivity.this;
recyclerView=(RecyclerView)findViewById(R.id.recyclerViewId);
/*notificationListShowAdapter=new NotificationListShowAdapter(contextNotificationActivity,list);
LinearLayoutManager layoutManager=new LinearLayoutManager(contextNotificationActivity);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationListShowAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(contextNotificationActivity,
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
notificationListShowAdapter.notifyDataSetChanged();*/
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(broadcastReceiver,new IntentFilter("Notification"));
}
private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Receiver",Toast.LENGTH_LONG).show();
String result=intent.getStringExtra("Result");
Log.v("Brd",intent.getStringExtra("Result"));
JSONObject jsonObject= null;
list=new ArrayList<>();
try {
jsonObject = new JSONObject(result);
// JSONObject codeObj=jsonObject.optJSONObject("code");
JSONArray jsonArray=jsonObject.getJSONArray("payload");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=new JSONObject(jsonArray.optString(i));
NotificationDataClass notificationDataClass=new NotificationDataClass();
notificationDataClass.setName(jsonObject1.getString("Name"));
notificationDataClass.setRemarks(jsonObject1.getString("Remarks"));
Log.v("hsdgfjgsdh", String.valueOf(jsonObject1.getInt("Type")));
if(jsonObject1.getInt("Type")==1){
notificationDataClass.setInout("In");
}else {
notificationDataClass.setInout("Out");
}
notificationDataClass.setTime(jsonObject1.getString("DateTime"));
list.add(i,notificationDataClass);
}
notificationListShowAdapter=new NotificationListShowAdapter(context,list);
LinearLayoutManager layoutManager=new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationListShowAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context,
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
notificationListShowAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(broadcastReceiver);
}
}
serviceClass:
public class ServiceClass extends Service {
GetPostAsyncTask_ServiceClass backgroundTask;
Context context;
Handler handler;
Runnable runnable;
LocalBroadcastManager localBroadcastManager;
int iny=1;
#Override
public void onCreate() {
super.onCreate();
localBroadcastManager=LocalBroadcastManager.getInstance(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context=getApplicationContext();
handler=new Handler();
runnable=new Runnable() {
#Override
public void run() {
String queryForNotification=null;
try {
queryForNotification = URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode("03/13/2017", "UTF-8");
Log.v("INRTR","out"+iny++);
backgroundTask=new GetPostAsyncTask_ServiceClass(context);
backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"GET","GetHrOnDutyActivityByDate?"+queryForNotification,"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(1000);
handler.postDelayed(runnable,10000);
}
};
handler.postDelayed(runnable,10000);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Asynctask
private class GetPostAsyncTask_ServiceClass extends AsyncTask<String, Void, String> {
// public AsyncResult asyncResult;
ProgressDialog progressDialog;
private final String baseUrl = "http://192.168.0.6:880/MobileAPI/";
Context context;
GetPostAsyncTask_ServiceClass(Context context) {
this.context = context;
// this.asyncResult = asyncResult;
}
#Override
protected void onPreExecute() {
//Toast.makeText(context,"Loading..",Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(context);
// progressDialog.show();
}
#Override
protected String doInBackground(String... args) {
try {
// setting the URL
URL url = new URL(baseUrl + args[1]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.addRequestProperty("Apiuser", "SDLPayrollAPI");
httpURLConnection.addRequestProperty("Apikey", "DFGHJ*UH45445^TY");
// setting the method type
httpURLConnection.setRequestMethod(args[0]);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// setting the identification key name with query params
bufferedWriter.write(args[2]);
bufferedWriter.flush();
bufferedWriter.close();
httpURLConnection.connect();
String line = "";
String res = "";
// prepare the output buffer
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
res += line;
}
inputStream.close();
httpURLConnection.disconnect();
return res.toString();
} catch (IOException e) {
Log.v("PesDSS","doBCa"+e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("PesDSS","out"+result);
Intent intent1;
// progressDialog.dismiss();
if (result != null) {
// asyncResult.asyncResult(result);
Log.v("PesDSS","in"+result);
//notification
NotificationCompat.Builder notification=new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.systech_logo)
.setContentTitle("Notification")
.setContentText("Delivered")
.setAutoCancel(true)
;
intent1 = new Intent(context, NotificationActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setAction("Notification");
intent1.putExtra("Result",result);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
TaskStackBuilder taskStackBuilder=TaskStackBuilder.create(context);
taskStackBuilder.addParentStack(NotificationActivity.class);
taskStackBuilder.addNextIntent(intent1);
PendingIntent pendingIntent=taskStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,intent1,PendingIntent.FLAG_CANCEL_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notification.build());
}
}
}
}
Notification data class:
public class NotificationDataClass {
String name;
String remarks;
String inout;
String time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getInout() {
return inout;
}
public void setInout(String inout) {
this.inout = inout;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
I tried to follow solutions from Stack Overflow but I could not solve it. Any help would be appreciated!
FYI onReceive() is called only when your current activity is in foreground or visible. For doing task on click of notification, when your activity/app is in background you should also do the same thing in onCreate() which you have done in onReceive() like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
Intent notificationIntent = getIntent.getStringExtra("Result");
if(notificationIntent != null){
//do whatever you have done in onReceive().
}
}
Related
I have a regular class (SOAP.java) which I added a function to call a webservice, I have the URL and other informations in res/values/strings.xml.
My Intent Service (which is called every 2 minutes) and a Fragment of my App are using the function in SOAP.java, but I can't get access to the strings, error:
08-19 03:47:19.730 16543-17323/fr.solutis.solutis E/AndroidRuntime﹕
FATAL EXCEPTION: IntentService[EnvoieService]
Process: fr.solutis.solutis, PID: 16543
java.lang.NullPointerException
at fr.solutis.solutis.SOAP.(SOAP.java:22)
at fr.solutis.solutis.notifications.EnvoieService.onHandleIntent(EnvoieService.java:96)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
SOAP.java:
public class SOAP {
private Context context;
public SOAP(Context current){
this.context = current;
}
String NAMESPACE = context.getResources().getString(R.string.NAMESPACE);
String URL = context.getResources().getString(R.string.URL);
String SOAP_ACTION = context.getResources().getString(R.string.SOAP_ACTION);
private static String TAG = SOAP.class.getSimpleName();
public Reponse envoieDemande(String method, String xml) {
code
}
}
IntenService:
public class EnvoieService extends IntentService {
DatabaseHandler db = new DatabaseHandler(this);
public EnvoieService() {
super("EnvoieService");
}
#Override
protected void onHandleIntent(Intent intent) {
List<Demande> demandes = db.getAllDemandesRenvoie();
String TAG = EnvoieService.class.getSimpleName();
if (!(demandes.isEmpty())) {
for (Demande cn : demandes) {
...
SOAP soap = new SOAP(this);
Reponse ret = soap.envoieDemande("SendLead", xml);
}
} else {
cancelAlarm();
}
}
public void cancelAlarm() {
Intent intent = new Intent(getApplicationContext(), EnvoieReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, EnvoieReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pIntent);
}
}
Fragment:
public class DemandeGratuite extends android.support.v4.app.Fragment {
...
{
{
{
{
{
{
{
{
AsyncSoapCall task = new AsyncSoapCall();
task.execute();
getChildFragmentManager().popBackStack();
mListener.onInteraction(6);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
}
);
}
private class AsyncSoapCall extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
SOAP soap = new SOAP(getContext());
Reponse ret = soap.envoieDemande("SendLead", xml);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
}
Resources cannot be accesed from the context of a service. You must use the context of an activity or u can try to use this class
public class App extends Application {
private static Context mContext;
public static Resources getResources() {
return mContext.getResources();
}
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
}
and then use the function App.getResources().getString(your_string_id) from wherever you want
i want to send a list from Background service to activity in android
public class MyService extends Service{
private String receiverUserInfoId;
private String loginUserInfoId;
private String orgMsgThreadId;
private String userName = "Vipin";
DatabaseHelper db;
MessageListActivity ms;
private String userAvatarURL;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
db = new DatabaseHelper(getApplicationContext());
Bundle extra = intent.getExtras();
loginUserInfoId = extra.getString("LoginUserInfoId");
receiverUserInfoId=extra.getString("UserInfoId");
orgMsgThreadId = extra.getString("OrgMessageThreadId");
userName=extra.getString("UserName");
userAvatarURL=extra.getString("UserAvatarURL");
new syncMessageFromServer().execute();
new SyncPendingMessageToServer();
return super.onStartCommand(intent, flags, startId);
}
private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
//progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetMessage?loginUserInfoId=" + loginUserInfoId + "&recieverUserInfoId=" + receiverUserInfoId + "&isPendingToSynce=" + true);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i <= jArray.length() - 1; i++) {
JSONObject row = jArray.getJSONObject(i);
ChatMessage cm = new ChatMessage();
cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
cm.setSenderUserInfoId(row.getString("SenderUserId"));
cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
cm.setMessageStatus("SENT");
cm.setIsPending(0);
cm.setMessageText(row.getString("MessageText"));
cm.setMediaURL(offlineFileURL);
cm.setThumbImage(offlineFileURL);
cm.setMediaMIMEType("");
cm.setMediaSize(0);
cm.setMediaName("");
cm.setLatitude("");
cm.setLongitude("");
cm.setSendTimeStamp(row.getString("SendTime"));
cm.setReceiveTimeStamp(row.getString("ReadTime"));
long messageThreadId = db.SendMessage(cm);
MessageListActivity mLA = new MessageListActivity();
mLA.SetListData(cm);
}
} catch (JSONException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new syncMessageFromServer().execute();
}
}
}
i want to send ChatMessage to the SetListData() function in MessageListActivity class how can i do this. just i want to refresh my list adapter to new message fetched by the server
You need to use a messenger if you want to communicate with the activity. Change your service like this:
public class MyService extends Service{
public static int MESSENGER = 1;
public static int JSONARRAY = 2;
private String receiverUserInfoId;
private String loginUserInfoId;
private String orgMsgThreadId;
private String userName = "Vipin";
DatabaseHelper db;
MessageListActivity ms;
private String userAvatarURL;
Messenger messageActivity;
final Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch(msg.what){
case MESSENGER:
messageActivity = msg.replyTo;
break;
}
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
db = new DatabaseHelper(getApplicationContext());
Bundle extra = intent.getExtras();
loginUserInfoId = extra.getString("LoginUserInfoId");
receiverUserInfoId=extra.getString("UserInfoId");
orgMsgThreadId = extra.getString("OrgMessageThreadId");
userName=extra.getString("UserName");
userAvatarURL=extra.getString("UserAvatarURL");
new syncMessageFromServer().execute();
new SyncPendingMessageToServer();
return super.onStartCommand(intent, flags, startId);
}
private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
//progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetMessage?loginUserInfoId=" + loginUserInfoId + "&recieverUserInfoId=" + receiverUserInfoId + "&isPendingToSynce=" + true);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray jArray = new JSONArray(str);
messageActivity.send(Message.obtain(null, JSONARRAY, jArray.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new syncMessageFromServer().execute();
}
}
}
And in your activity add the following methods:
public class MyListActivity extends Activity{
public static Messenger mService = null;
public final Messenger mMessenger = new Messenger(new IncomingHandler());
public boolean mIsBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_participant);
doBindService();
}
public void doBindService() {
if (!mIsBound) {
context.bindService(new Intent(context,
MyService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, MyService.MESSENGER);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyService.JSONARRAY:
buildTheChatMessage((JsonArray)msg.obj);
break;
default:
super.handleMessage(msg);
}
}
}
public void buildTheChatMessage(JsonArray arr){
ChatMessage cm = new ChatMessage();
cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
cm.setSenderUserInfoId(row.getString("SenderUserId"));
cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
cm.setMessageStatus("SENT");
cm.setIsPending(0);
cm.setMessageText(row.getString("MessageText"));
cm.setMediaURL(offlineFileURL);
cm.setThumbImage(offlineFileURL);
cm.setMediaMIMEType("");
cm.setMediaSize(0);
cm.setMediaName("");
cm.setLatitude("");
cm.setLongitude("");
cm.setSendTimeStamp(row.getString("SendTime"));
cm.setReceiveTimeStamp(row.getString("ReadTime"));
setListData(cm);
}
}
This way your activity is bound to the service and you can communicate between them. I wish you get the idea from this code and implement what you need.
Here's a source to read more about this methods.
I'm try to writing an online game with a socket connection.
So I use asynctask to make a socket connection.
SocketServer.java
public class SocketServer{
private MyCustomListener listener;
private String ip = "127.0.0.1";
private int port = 4444;
#SuppressWarnings("unused")
private Context context;
private SocketAsync socketAsync;
private String dataInput, username;
public SocketServer(Context context) {
this.context = context;
}
public void setOnRecieveMsgListener(MyCustomListener listener) {
this.listener = listener;
}
public void connect() {
socketAsync = new SocketAsync();
socketAsync.execute();
}
public void sentData(String x, String y, String z) {
dataInput = null;
JSONObject object = new JSONObject();
// JSON Encode
socketAsync.sentJSON(object);
}
private class SocketAsync extends AsyncTask<Void, Void, String> {
private Socket socket;
private PrintWriter printWriter;
#Override
protected String doInBackground(Void... params) {
try {
socket = new Socket(InetAddress.getByName(ip),port);
OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
printWriter = new PrintWriter(streamOut);
streamOut.flush();
BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
Looper.prepare();
while(socket.isConnected()) {
try {
dataInput = streamIn.readLine();
listener.onRecieveMessage(new MyListener(dataInput));
}
catch(Exception e) {}
}
Looper.loop();
}
catch(Exception e) {}
return null;
}
public void sentJSON(JSONObject object) {
if(socket.isConnected()) {
try {
printWriter.println(object.toString());
printWriter.flush();
}
catch(Exception e) {}
}
}
}
}
Login.class
public class Login extends Activity implements MyCustomListener {
JSONObject object;
SocketServer socketserver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
socketserver = new SocketServer(this);
socketserver.setOnRecieveMsgListener(this);
socketserver.connect();
button();
}
private void button() {
Button loginBt = (Button)findViewById(R.id.login_bt);
final EditText un = (EditText)findViewById(R.id.username);
final EditText ps = (EditText)findViewById(R.id.password);
final String[] logindata = new String[2];
loginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logindata[0] = un.getText().toString();
logindata[1] = ps.getText().toString();
socketserver.setUsername(logindata[0]);
socketserver.sentData("SERVER", "TEST", "login");
}
});
}
private void toMainScreen() {
Intent x = new Intent(this,Main.class);
startActivity(x);
}
#Override
public void onRecieveMessage(MyListener ml) {
try {
JSONObject json = new JSONObject(ml.getMsgStr());
System.out.println(json.getString("content"));
if(json.getString("content").equals("TRUE")) {
toMainScreen();
}
else
Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.e("## JSON DECODE", e.toString());
e.printStackTrace();
}
}
}
Main.class
public class Main extends Activity implements MyCustomListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//do some thing
}
#Override
public void onRecieveMessage(MyListener ml) {
System.out.println("MAIN : " + ml.getMsgStr());
}
}
so how can I pass object "socketserver" from login class to main class?
or is there an other way to do something like this?
sorry for my poor english.
You should not try to pass an instance of SocketServer around. One of it's properties is context which means you should not used it outside the original context it was created in (i.e. activity it was created in) or you'll have memory leaks.
Your SocketServer class needs IP and port. This is the kind of information that you should pass between activities and then use that to create another instance of your SocketServer class.
This is my Service which does network operation. But it is throwing NetworkonMainThreadException which i understand android upper version doesn't allows network operation under main thread. Now i want to use Async Task for this purpose. I am not sure which are all code i need to add under Async Task from Service Class to actually make the code complete. Below is my Service Code :
public class NewsTickerDataService extends Service {
#Override
public void onStart(Intent aIntent, int aStartId) {
super.onStart(aIntent, aStartId);
RemoteViews _views = buildUpdatedViews(this);
ComponentName _widget =
new ComponentName(this, NewsTicker.class);
AppWidgetManager _manager =
AppWidgetManager.getInstance(this);
_manager.updateAppWidget(_widget, _views);
}
#Override
public IBinder onBind(Intent aParamIntent) {
// not supporting binding
return null;
}
private RemoteViews buildUpdatedViews(Context aContext) {
List<Story> _stories = getStories();
RemoteViews _result = new RemoteViews(
aContext.getPackageName(),
R.layout.activity_main
);
if (_stories.isEmpty()) {
_result.setTextViewText(R.id.title,
"Sadly there's nothing to read today.");
} else {
_result.setTextViewText(
R.id.title, _stories.get(0).getTitle());
}
return _result;
}
private List<Story> getStories() {
try {
URL _url = new URL("http://search.twitter.com" +
"/search.atom?q=%23uml&" +
"result_type=mixed&count=5"
);
InputStream _in = _url.openStream();
return parse(new InputSource(_in));
} catch (Exception anExc) {
Log.e("NewsTicker", anExc.getMessage(), anExc);
return new ArrayList<Story>();
}
}
private List<Story> parse(InputSource aSource)
throws Exception {
SAXParserFactory _f = SAXParserFactory.newInstance();
SAXParser _p = _f.newSAXParser();
XMLReader _r = _p.getXMLReader();
AbstractParser _h = AbstractParser.newAtomParser();
_r.setContentHandler(_h);
_r.parse(aSource);
return _h.getStories();
}
}
Async Task Code :
public class YourAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// your load work
//return myString;
}
#Override
protected void onPostExecute(String result) {
}
}
Can someone please help me to integrate Async Task into same code. Thanks
Yes, I'd suggest IntentService too!
IntentService example
public class MyService extends IntentService {
private int STOP_DOWNLOAD = false;
public static int UPDATE_PROGRESS = 0;
public MyService() {
super("myservice");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
// Network Task : download ?
// Send some data to the receiver
Bundle resultData = new Bundle();
resultData.putInt("progress", progress);
receiver.send("update", resultData);
}
private void stopDownload() {
this.STOP_DOWNLOAD = true;
// Stop the download : use this boolean into onHandleIntent
}
}
The receiver
public class MyReceiver extends ResultReceiver {
Context context;
public MyReceiver(Context mContext) {
super(handler);
context = mContext;
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == "update") {
String something = resultData.getString(MyService.SOMETHING);
}
}
}
Start the service in an Activity : startService(...)
From the onStart() of your service class make network operation
YourAsyncTask.execute(url);
Async task code
public class YourAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// your load work
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
//return myString;
}
#Override
protected void onPostExecute(String result) {
//HERE CALL YOUR PARSE METHOD
//AFTER PARSING CALL buildUpdatedViews(Context aContext , stories)
}
}
i have search and not found the answer. I want to call startActvity(newintent), but the page not change.
This my code:
public class MainActivity extends Activity {
private TextView IdPeserta, Password;
//private ArrayList<NameValuePair> authentication;
#SuppressWarnings("unused")
//private String temp, _nama = "";
//private readURL rL;
public static String username = "";
public static String password = "";
public static String status = "FALSE";
public void setPassword(String password){
MainActivity.password = password;
}
public void setUsername(String username){
MainActivity.username = username;
}
public void setStatus(String status){
MainActivity.status = status;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
IdPeserta = (TextView) findViewById(R.id.idPeserta);
Password = (TextView) findViewById(R.id.password);
}
public void Login(View view){
setUsername(IdPeserta.getText().toString());
setPassword(Password.getText().toString());
if((IdPeserta.getText().length() > 0 && Password.getText().length() > 0)){
RestTask task = new RestTask();
task.applicationContext = MainActivity.this;
task.execute();
}else{
Toast.makeText(this,"fill Id Peserta and Password 1", 0).show();
}
}
public void authenticate(){
if(status.equals("TRUE")){
Intent i = new Intent(MainActivity.this, Home.class);
//PendingIntent pending = PendingIntent.getActivity(this, 0, i, 0);
startActivity(i);
finish();
}else if(status.equals("FALSE")){
Log.d("gagal", "coba lagi");
}
}
public static String getService() {
String responseString = null;
String baseurlString = "http://10.0.2.2:8080/UjianServices/authentikasi.php";
RestClient client = new RestClient(baseurlString);
client.AddParam("id_peserta", MainActivity.username);
client.AddParam("password", MainActivity.password);
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
Log.d("error", e.getMessage());
//e.printStackTrace();
}
responseString = client.getResponse();
return responseString;
}
public class RestTask extends AsyncTask<Object, Object, Object>{
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
}
#Override
protected void onPostExecute(Object result) {
this.dialog.cancel();
String status = result.toString();
setStatus(status);
authenticate();
}
#Override
protected Object doInBackground(Object... arg0) {
return MainActivity.getService();
}
}
}
When i did not using the RestTask it can change the page. How i change my activity?
because applicationContext is null you have not initialize applicationContext before using it for showing ProgressDialog from onPreExecute .
you need to initialize applicationContext before using for showing ProgressDialog or just use MainActivity.this as :
#Override
protected void onPreExecute() {
applicationContext=MainActivity.this; //<<< initialize context here
this.dialog = ProgressDialog.show(applicationContext,
"Calling", "Time Service...", true);
}