|
Thank you,
I will try these options and see if that fixes it.
Thank you for the help.
|
|
|
|
|
I just fixed it! Thank you for your help otherwise I would have been stuck here for a month.
|
|
|
|
|
Hello to all,
I'm looking for somebody to write app with in AS. All data/project is ready just programming left to be done. Since I'm only 'a year experienced' beginner, I wish to work with somebody more advanced in java-android programming. There is a big chance of success so we can work as co-creators in coming projects too.
|
|
|
|
|
Sorry, but these forums are for technical questions, not recruitment. Try freelancers.com.
|
|
|
|
|
|
Can you please explain what type of project it is? Actually I have experience in building projects for some particular domains. Please let me know about the industry and other details that you can share.
|
|
|
|
|
Hi,
I have a lot of database text files arranged inside folders and subfolders. I want to restrict the files from accessing externally from the app. So asset/ raw folder is the best option and each file size is less than 50kb. And in asset folder the arrangement is similar to file system and in raw folder its based on id's. So i opt for asset folder.
The selection of the database file is done by the user. So a search dialog window for browsing the file would be the better option. But i don't find any sample code for accessing a asset file system using dialog window. Is it possible?.
Thanks
Nikhil.
|
|
|
|
|
NiKHiLMS wrote: But i don't find any sample code for accessing a asset file... Have you tried something like this?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Thanks for the reply.
Actually I need a sample code for accessing a file in asset folder with the help of file browsing dialog window not this.
Anyway i dropped the plan, instead of file browsing dialog window, listview will be a better option. Files and folders inside the asset folder can be displayed in ListView and user can select what they need.
|
|
|
|
|
NiKHiLMS wrote: ...instead of file browsing dialog window, listview will be a better option. Those two things are mutually exclusive. Whether you have a dialog or not, you still need a container (e.g., ListView ) for the filenames.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Hello all. From out of 10 dialogs, I need one of the dialogs to start with landscape orientation. No other activity, fragment and dialog will be started with landscape orientation except this one dialog.
I have absolutely no idea how do I make this happen? Do I create some custom control ?
Thanks for any input.
|
|
|
|
|
I have an Android application where customers can purchase and put orders
Every customer can put order and I just have one `JSON` file in the `PHP` server to collect the orders from different customers
The problem is if one customer puts his/her order, the `JSON` file shall be locked in order to prevent collision and if it is locked, how can another customer put order at the exact same time?
To solve this issue, and for test, I decided to have a folder in the server where every customer (who is going to put an order) can put his unique ID there (uploading a text file with the name of the customer's ID) and I just read that folder to see who has put any order and then I delete the file which was uploaded by the customer indicating he/she has just put an order to be ready from another order from that customer
(every customer creates a folder with his/her unique ID name to put detailed list of his/her orders and this is handled by PHP code)
It works fine but does not seem to be a true manner from performance point of view
Any suggestion?
|
|
|
|
|
The PHP server should be able to handle multiple orders, just like any other web server.
|
|
|
|
|
The point is writing to the same file at the same time and as I searched it may create corruption
|
|
|
|
|
Exactly why I made my comment. You should not try to write to a single file in a multi-user application; it makes no sense.
|
|
|
|
|
AndroidVH wrote: one `JSON` file in the `PHP` server to collect the orders from different customers Unlike an ASP or PHP page, a JSON file does not "collect" anything. Based on what you've provided, unless you are doing something totally wrong, there should be no way for it to become locked. If multiple clients request the same JSON file, the web server will deliver the file to each client without issue.
AndroidVH wrote:
Any suggestion? The whole "upload a file containing a customer number and/or order" approach seems way wrong to me.
When you make contact with a web server, a one-on-one relationship has been established. When you interact with a web page (e.g., PHP file), you are doing so with your "copy" of it. If some other client is also interacting with that same page, again it's on their own "copy" of it. The web server keeps track of all those connections (up to some upper limit).
Admittedly, I may be completely wrong on this. It borders on ecommerce which I have zero experience with. But what you are doing just seems kludgy and prone to error.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Sorry, I meant the orders are stored in the JSON by PHP code
I changed the process so as to prevent writing to the same file by different clients
|
|
|
|
|
I have to record a live audio/vedio and convert it into udp packets and broadcast it over wifi but not working after recording.
This is my code
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
random = new Random();
startAudioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkPermission()) {
audioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/" + createRandomFile(5) + "Recording.3gp";
mediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
startListener();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
startAudioButton.setEnabled(false);
stopAudioButton.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording Started ", Toast.LENGTH_SHORT).show();
}else{
requestPermission();
}
}
});
stopAudioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Recording Completed",Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
stopAudioButton.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
stopAudioButton.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(getApplicationContext(),"Recording Completed",Toast.LENGTH_SHORT).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) throws IllegalArgumentException,
SecurityException, IllegalStateException {
try{
startAudioButton.setEnabled(false);
stopAudioButton.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioSavePathInDevice);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(),"Recording Playing",Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopAudioButton.setEnabled(false);
stopAudioButton.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaRecorderReady();
}
}
});
}
private void init() {
startAudioButton = ( Button)findViewById(R.id.button);
stopAudioButton = ( Button)findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button) findViewById(R.id.button4);
stopAudioButton.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
}
private void mediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(audioSavePathInDevice);
}
private String createRandomFile(int i) {
StringBuilder stringBuilder = new StringBuilder( i );
int j =0;
while (j<i){
stringbuilder.append(randomaudiofilename.charat(random.nextint(randomaudiofilename.length())));
="" j++;
="" }
="" return="" stringbuilder.tostring();
="" }
="" private="" void="" startlistener()="" {
="" create="" listener="" thread
="" listen="true;
" thread="" listenthread="new" thread(new="" runnable()="" {
="" <a="" href="https://www.codeproject.com/Members/override">@Override
public void run() {
try {
Log.i(LOG_TAG, "Listener started!");
DatagramSocket socket = new DatagramSocket(BROADCAST_PORT);
byte[] buffer = new byte[BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, BUF_SIZE);
while(LISTEN) {
try {
socket.send(packet);
Log.i(LOG_TAG, "Listening for packets");
socket.receive(packet);
String data = new String(buffer, 0, packet.getLength());
Log.i(LOG_TAG, "Packet received from "+ packet.getAddress() +" with contents: " + data);
// String action = data.substring(0, 4);
}
catch(SocketTimeoutException e) {
if(!IN_CALL) {
Log.i(LOG_TAG, "No reply from contact. Ending call");
endCall();
return;
}
}
catch(IOException e) {
}
}
Log.i(LOG_TAG, "Listener ending");
socket.disconnect();
socket.close();
return;
}
catch(SocketException e) {
Log.e(LOG_TAG, "SocketException in Listener");
endCall();
}
}
});
listenThread.start();
}
private void stopListener() {
// Ends the listener thread
LISTEN = false;
}
private void endCall() {
// Ends the chat sessions
stopListener();
if(IN_CALL) {
call.endCall();
}
finish();
}
}
When i am using only MediaRecorder for recording it working but when i try for udp packet conversion it not ,basically not getting how to club recording and udp packet code.
modified 22-Jun-18 5:26am.
|
|
|
|
|
What does "not working" mean? Please format your code properly (and remove any lines not related to the problem), and give some useful details as to the actual problem.
|
|
|
|
|
I was trying to fetch JSON data into a RecyclerView using Retrofit 2. I also implemented pagination. Now for testing, I changed the JSON URL as if it will only show `5`items per page. The page number can be changed by adding "&page=`PAGE#`" at the end of the JSON URL (where PAGE# is integer value starting from 1 and if no Page no is mentioned, it will show by default the first page).
Problem: I have successfully added every page into the Recyclerview. But, it is adding the last page items twice, sometimes it is adding 3 times. Like this.
I am unable to find the problem. The step by step debugging does not help. Please help me. I am learning these so if you help me I would really appreciate it.
The JSON looks as follows:
[{
"id": 369,
"guid": {
"rendered": "URL?p=369"
},
"title": {
"rendered": "Shudder"
},
"content": {
"rendered": "<p>Shaking of body caused by fear.</p>\n<p>ভয়ের কাঁপুনি</p>\n<p> </p>\n",
"protected": false
},
"post_categories": [
"English",
"Father's Help",
"Madhyamik",
"Prose",
"Seen",
"Word Nest"
]
},
{
"id": 548,
"guid": {
"rendered": "URL?p=548"
},
"title": {
"rendered": "Swami went ______ school feeling that he was ______ worst boy ______ earth."
},
"content": {
"rendered": "<p>Swami went to school feeling that he was the worst boy on earth.</p>\n",
"protected": false
},
"post_categories": [
"Articles and Prepositions",
"English",
"Grammar",
"Madhyamik"
]
},
{
"id": 528,
"guid": {
"rendered": "URL?p=528"
},
"title": {
"rendered": "Teacher said "Explain the law of gravitation"."
},
"content": {
"rendered": "<p>Teacher ordered to explain the law of gravitation.</p>\n",
"protected": false
},
"post_categories": [
"English",
"Grammar",
"Madhyamik",
"Narration"
]
},
{
"id": 552,
"guid": {
"rendered": "URL?p=552"
},
"title": {
"rendered": "Test Post "Image""
},
"content": {
"rendered": "<p><img src=\"http://latex.codecogs.com/gif.latex?x^{2}+2xy+y^{2}&space;=&space;45\" alt=\"x^{2}+2xy+y^{2} = 45\" align=\"absmiddle\" /></p>\n<p> </p>\n<p><img src=\"http://aseducationsolution.com/wp-content/uploads/2018/06/blur-1868068_1920-150x150.jpg\" alt=\"\" width=\"150\" height=\"150\" class=\"alignnone wp-image-312 size-thumbnail\" /></p>\n<p> </p>\n<p>let us take <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\fn_cm&space;\\small&space;\\left&space;(&space;a+b&space;\\right&space;)^{3}&space;+&space;\\alpha&space;\\lambda&space;\\varepsilon&space;\\Delta&space;ABC\" alt=\"\\inline \\fn_cm \\small \\left ( a+b \\right )^{3} + \\alpha \\lambda \\varepsilon \\Delta ABC\" align=\"absmiddle\" /></p>\n<p> </p>\n<p>another example <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\small&space;a^{3}+b^{3}&space;=&space;123\" alt=\"\\inline \\small a^{3}+b^{3} = 123\" align=\"absmiddle\" /> check alignment is correct or not.</p>\n<p> </p>\n<p><img src=\"http://latex.codecogs.com/svg.latex?\\dpi{120}&space;\\small&space;\\frac{a}{b}+2c\" alt=\"\\dpi{120} \\small \\frac{a}{b}+2c\" align=\"absmiddle\" /> SVG</p>\n<p><img src=\"http://latex.codecogs.com/gif.latex?\\dpi{120}&space;\\small&space;\\sum&space;a+b+c+....\" alt=\"\\dpi{120} \\small \\sum a+b+c+....\" align=\"absmiddle\" /> GIF</p>\n<p> </p>\n<p>Equation example</p>\n<p> </p>\n<p> </p>\n",
"protected": false
},
"post_categories": [
"English",
"Madhyamik"
]
},
{
"id": 514,
"guid": {
"rendered": "URL?p=514"
},
"title": {
"rendered": "Time when Swami complained of a headache _________?"
},
"content": {
"rendered": "<p>9 A.M.</p>\n",
"protected": false
},
"post_categories": [
"English",
"Father's Help",
"Fill in from Text",
"Madhyamik",
"Prose",
"Seen"
]
}
]
Now, when there are no posts available as per the PAGE# of JSON URL, it will show the following JSON:
{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
Now, if you look at my code for the fragment:
private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager mLayoutManager;
private ArrayList < Model > list;
private RecycleAdapter adapter;
private View rootView;
private int pageNo = 2;
ProgressBar progress;
public String url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey;
public static List < WPPost > mListPost;
Boolean isScrolling = false;
int currentItems, scrolledItems, totalItems;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.search_englishhome, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.postList);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLayoutManager);
DividerItemDecoration itemDecor = new DividerItemDecoration(Objects.requireNonNull(getActivity()), mLayoutManager.getOrientation());
recyclerView.addItemDecoration(itemDecor);
list = new ArrayList < > ();
progress = (ProgressBar) rootView.findViewById(R.id.recyclerprogress);
progress.setVisibility(View.GONE);
adapter = new RecycleAdapter(list, getActivity());
recyclerView.setAdapter(adapter);
getRetrofit();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = mLayoutManager.getChildCount();
totalItems = mLayoutManager.getItemCount();
scrolledItems = mLayoutManager.findFirstVisibleItemPosition();
if (isScrolling = (currentItems + scrolledItems == totalItems)) {
isScrolling = false;
url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey + "&page=" + pageNo;
progress.setVisibility(View.VISIBLE);
if (mListPost != null) {
getRetrofit();
} else {
progress.setVisibility(View.GONE);
}
}
}
});
return rootView;
}
public void getRetrofit() {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RetrofitArrayAPI.baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
final Call < List < WPPost >> call = service.getPostInfo(url);
call.enqueue(new Callback < List < WPPost >> () {
@Override
public void onResponse(Call < List < WPPost >> call, Response < List < WPPost >> response) {
Log.e("EnglishHome", "Response" + response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
pageNo++;
for (int i = 0; i < response.body().size(); i++) {
String tempCode = response.body().get(i).getCode();
int tempID = response.body().get(i).getId();
String tempTitle = response.body().get(i).getTitle().getRendered();
tempTitle = tempTitle.replace(""", "\"");
tempTitle = tempTitle.replace(""", "\"");
String tempContent = response.body().get(i).getContent().getRendered();
List < String > catitemnames = response.body().get(i).getPostCategories();
catitemnames.remove("Madhyamik");
catitemnames.remove("English");
catitemnames.remove("Grammar");
catitemnames.remove("Seen");
catitemnames.remove("Prose");
catitemnames.remove("Poem");
String categorynames = catitemnames.toString();
categorynames = categorynames.substring(1, categorynames.length() - 1);
if (tempCode != null) {
response.body().clear();
list.clear();
isScrolling = false;
mListPost.clear();
return;
} else {
list.add(new Model(tempID, tempTitle, tempContent, categorynames));
}
}
mListPost.clear();
progress.setVisibility(View.GONE);
} else {
progress.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call < List < WPPost >> call, Throwable t) {
}
});
}
}
My RecyclerView Adapter looks like:
public class RecycleAdapter extends RecyclerView.Adapter {
private ArrayList < Model > dataset;
private Context mContext;
public RecycleAdapter(ArrayList < Model > mList, Context context) {
this.dataset = mList;
this.mContext = context;
}
public static class ListTypeViewHolder extends RecyclerView.ViewHolder {
TextView title, categories;
RelativeLayout relativeLayout;
ListTypeViewHolder(View itemView) {
super(itemView);
this.title = (TextView) itemView.findViewById(R.id.texttitlesofrv);
this.categories = (TextView) itemView.findViewById(R.id.textcategoryrv);
this.relativeLayout = (RelativeLayout) itemView.findViewById(R.id.recyclerrow);
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
return new ListTypeViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
final Model object = dataset.get(holder.getAdapterPosition());
((ListTypeViewHolder) holder).title.setText(object.title);
((ListTypeViewHolder) holder).categories.setText(object.categoriesnames);
((ListTypeViewHolder) holder).relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, FullPostView.class);
intent.putExtra("itemPosition", holder.getAdapterPosition());
intent.putExtra("postID", object.postid);
intent.putExtra("postTitle", object.title);
intent.putExtra("postContent", object.content);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return dataset.size();
}
}
WPPOST POJO:
public class WPPost {
@SerializedName("code")
@Expose
private String code;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("guid")
@Expose
private Guid guid;
@SerializedName("title")
@Expose
private Title title;
@SerializedName("content")
@Expose
private Content content;
@SerializedName("post_categories")
@Expose
private List < String > postCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Guid getGuid() {
return guid;
}
public void setGuid(Guid guid) {
this.guid = guid;
}
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
public List < String > getPostCategories() {
return postCategories;
}
public void setPostCategories(List < String > postCategories) {
this.postCategories = postCategories;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
MODEL Class:
public class Model {
public int postid;
public String title;
public String content;
public String categoriesnames;
public Model(int mID, String mTitle, String mContent, String mCategorynames) {
this.postid = mID;
this.title = mTitle;
this.content = mContent;
this.categoriesnames = mCategorynames;
}
}
Thank you in advance.
|
|
|
|
|
Do I have the correct current version of Android Studio installed on my machine ?
When I follow the drop down menus: ...Help../..About... I see these words on my screen...
Quote: Android Studio 3.0.1 Build #AI-171.4443003, built on November 9th, 2017
JRE: 1.8.0-152-release-915-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 8.1 6.3
Is that correct for today ? November of last year ?
|
|
|
|
|
|
The latest version is
Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b02 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
I highly recommend downloading the new version. The performance boost it brings is epic.
|
|
|
|
|
You sir, are just plain cool. Thank you
|
|
|
|
|
Quote: I'm writing a program using bound service with Inter Process Communication(IPC). The goal is to send the generated data in a thread (DataExchange) from the service to the mainActivity, using Messenger and Hanler. When the data is placed in the message queue from run method, I'm unable to receive it in the activityHandler (mainActivity). fortunatly I can receive the data in the serviceHandler (Local communication), however when I try to send the same message from the serviceHandler (service) to activityHandler (mainActivity), I'm getting a FATAL EXCETION
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference
Someone please help
MainActivity
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int UPDATE = 2;
TextView textView;
Messenger activityMessenger;
boolean bound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R. id. textView);
Intent bindBtService = new Intent(this, BluetoothService.class);
bindService(bindBtService, serviceConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
activityMessenger = new Messenger(service);
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
unbindService(serviceConnection);
activityMessenger = null;
bound = false;
}
};
class activityHandler extends Handler{
@Override
public void handleMessage(Message msg) {
String received;
switch (msg.what){
case UPDATE:
received = msg.getData().getString("update");
Log.i(TAG, "From Run Method " + received);
textView.setText(received);
break;
default:
super.handleMessage(msg);
}
}
}
@Override
protected void onDestroy() {
unbindService(serviceConnection);
activityMessenger = null;
bound = false;
super.onDestroy();
}
}
Service
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
public class BluetoothService extends Service {
private static final String TAG = BluetoothService.class.getSimpleName();
private static final int SEND = 1;
private static final int UPDATE = 2;
private DataExchange dataExchange;
Messenger serviceMessenger = new Messenger(new ServiceHandler());
public BluetoothService() {
}
@Override
public void onCreate() {
super.onCreate();
dataExchange = new DataExchange(new ServiceHandler());
dataExchange.start();
}
@Override
public IBinder onBind(Intent intent) {
return serviceMessenger.getBinder();
}
class ServiceHandler extends Handler{
Messenger mess;
Message message;
String response = " ";
Bundle bundle = new Bundle();
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SEND:
response = msg.getData().getString("message");
Log.i(TAG, "Random Number: " + response );
message = Message.obtain(null, UPDATE);
bundle.putString("update", response);
message.setData(bundle);
try {
msg.replyTo.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
private class DataExchange extends Thread implements Runnable{
Handler serviceHandler;
public DataExchange(ServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
for (int i = 0; i < 100; i++){
String val = String.valueOf(i);
try {
Thread.sleep(1000);
Message msg = prepareMessage(val);
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Message prepareMessage(String string){
Bundle dataBundle = new Bundle();
Message result = serviceHandler.obtainMessage(SEND);
dataBundle.putString("message", string);
result.setData(dataBundle);
return result;
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.seber.lisah">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".BluetoothService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
|
|
|
|
|