When I try to start my IntenetService I get no errors, but it never hits the breakpoint in onHandleIntent
MainActivity.java
package com.peterchappy.filewatcher.activities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.peterchappy.filewatcher.R;
import com.peterchappy.filewatcher.services.FileDownloadService;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainActivity extends Activity {
public static final String INTENT_EXTRA_FILE_URL = "URL";
private FileDownloadBroadcastReceiver broadcastReceiver;
private Button go;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
go = (Button) findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadFile("http://www.reddit.com/");
}
});
}
#Override
protected void onStart() {
super.onStart();
broadcastReceiver = new FileDownloadBroadcastReceiver();
registerReceiver(broadcastReceiver, new IntentFilter(FileDownloadService.FILE_DOWNLOADED));
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
private void downloadFile(String text) {
Intent intent = new Intent(this, FileDownloadService.class);
intent.putExtra(INTENT_EXTRA_FILE_URL, text);
this.startService(intent);
}
private void readFileAndDisplayContent(String fileName) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private class FileDownloadBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String localFileName = intent.getStringExtra(FileDownloadService.INTENT_LOCAL_FILE_NAME);
readFileAndDisplayContent(localFileName);
}
}
}
FileDownloadService.java
package com.peterchappy.filewatcher.services;
import android.app.IntentService;
import android.content.Intent;
import com.peterchappy.filewatcher.activities.MainActivity;
import com.peterchappy.filewatcher.helpers.FileDownloader;
public class FileDownloadService extends IntentService {
public static final String INTENT_LOCAL_FILE_NAME = "local_file_name";
public static final String FILE_DOWNLOADED = "FILE_DOWNLOADED";
public FileDownloadService() {
super("FILE_DOWNLOAD_SERVICE");
}
#Override
protected void onHandleIntent(Intent intent) {
FileDownloader fileDownloader = new FileDownloader(this);
String localFileName = fileDownloader.downloadFile(intent.getStringExtra(MainActivity.INTENT_EXTRA_FILE_URL));
Intent resultIntent = new Intent(FILE_DOWNLOADED);
resultIntent.putExtra(INTENT_LOCAL_FILE_NAME, localFileName);
sendBroadcast(resultIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<service android:name=".filewatcher.services.FileDownloadService"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok, now I think I see it in your manifest. <service> tag is outside <application> tag, try moving it inside.
Related
I ask for help, there is a class for setting live wallpapers on android. Everything seems to be connected and should work as it should, but nothing works. Tell me what's wrong?
onCreateEngine is not called for some reason at startActivity.
package com.atticpic;
import android.os.Environment;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.service.wallpaper.WallpaperService;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.app.PendingIntent;
import android.app.Activity;
public class ReactVideoWallpaperModule extends ReactContextBaseJavaModule {
Context context;
private File file;
private VideoWallpaper mVideoWallpaper;
public ReactVideoWallpaperModule(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext.getApplicationContext();
}
#Override
public String getName() {
return "ReactVideoWallpaper";
}
#ReactMethod
void setWallpaperVideo(final String videoUri) {
mVideoWallpaper = new VideoWallpaper();
file = new File(videoUri);
if (!file.exists()) {
Log.i( null, "File not found: " + file);
}
mVideoWallpaper.setToWallPaper(context, file.getAbsolutePath());
}
public class VideoWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
Log.i( TAG, "( START VideoEngine )");
return new VideoWallpagerEngine();
}
private final String TAG = VideoWallpaper.class.getName();
private String sVideoPath;
protected int playheadTime = 0;
public void setToWallPaper(Context context,String videoPath) {
try {
context.clearWallpaper();
} catch (IOException e) {
e.printStackTrace();
}
sVideoPath = videoPath;
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
//intent.setAction(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT);
//intent.setClass(context, VideoWallpaper.class);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, VideoWallpaper.class));
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
class VideoWallpagerEngine extends Engine {
private final String TAG = getClass().getSimpleName();
private MediaPlayer mediaPlayer;
public VideoWallpagerEngine() {
super();
Log.i( TAG, "( VideoEngine )");
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(sVideoPath);
mediaPlayer.setLooping(true);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
Log.i( TAG, "onSurfaceCreated" );
super.onCreate(surfaceHolder);
}
#Override
public void onDestroy() {
Log.i( TAG, "onSurfaceCreated" );
super.onDestroy();
}
#Override
public void onVisibilityChanged(boolean visible) {
Log.i( TAG, "onSurfaceCreated" );
if (visible){
mediaPlayer.start();
}else {
mediaPlayer.pause();
}
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.i( TAG, "onSurfaceCreated" );
mediaPlayer.setSurface(holder.getSurface());
mediaPlayer.start();
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i( TAG, "onSurfaceCreated" );
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.i( TAG, "( INativeWallpaperEngine ): onSurfaceDestroyed" );
playheadTime = mediaPlayer.getCurrentPosition();
mediaPlayer.reset();
mediaPlayer.release();
}
}
}
}
Call to react native
const DownloadImage = async (item) => { const result = await NativeModules.ReactVideoWallpaper.setWallpaperVideo(dirFile); }
There is a video file, there are no errors, tell me what is wrong?
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.atticpic.ReactVideoWallpaperModule.VideoWallpaper"
android:exported="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER"
android:process=":wallpaper">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper" />
</service>
</application>
It is expected to be completed and as a result of success, the installation of video wallpapers is expected.
However, I try only when my app has a launcher property will the activity detect the NFC intent. Even if I have a intent filter in another application. Here is my manifest and both the activities. I even have foreground dispatch managed.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.melin.vustudentattendence">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<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=".AddStudentsActivity"></activity>
<activity android:name=".AddClassesActivity" />
<activity android:name=".AddTeachersActivity" />
<activity android:name=".TestActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity android:name=".ClassAttendenceActivity">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity
android:name=".LecutererClassesListActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".InstituteDashboardActivity" />
<activity android:name=".TodaysClassesActivity" />
<activity
android:name=".LecturerDashboardActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".LoginActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is my TestActivity.java
package com.melin.vustudentattendence;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipDescription;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class TestActivity extends AppCompatActivity {
public static final String TAG="NFCDemo";
private TextView mTextView;
private NfcAdapter mNfcAdapter;
public class NdefReaderTask extends AsyncTask<Tag,Void,String> {
#Override
protected String doInBackground(Tag... params) {
Tag tag = params[0];
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// NDEF is not supported by this Tag.
return null;
}
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord ndefRecord : records) {
if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported Encoding", e);
}
}
}
return null;
}
private String readText(NdefRecord record) throws UnsupportedEncodingException {
/*
* See NFC forum specification for "Text Record Type Definition" at 3.2.1
*
* http://www.nfc-forum.org/specs/
*
* bit_7 defines encoding
* bit_6 reserved for future use, must be 0
* bit_5..0 length of IANA language code
*/
byte[] payload = record.getPayload();
// Get the Text Encoding
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
// Get the Language Code
int languageCodeLength = payload[0] & 0063;
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
// e.g. "en"
// Get the Text
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
mTextView.setText("Read content: " + result);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
mTextView=(TextView)findViewById(R.id.textView_explanation);
mNfcAdapter= NfcAdapter.getDefaultAdapter(this);
if(mNfcAdapter==null){
Toast.makeText(this,"This device doesn't support NFC",Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mNfcAdapter.isEnabled()){
mTextView.setText("Nfc is disabled");
}else{
mTextView.setText(R.string.explanation);
}
handleIntent(getIntent());
}
#Override
protected void onResume() {
super.onResume();
setupForegroundDispatch(this, mNfcAdapter);
}
#Override
protected void onPause() {
stopForegroundDispatch(this,mNfcAdapter);
super.onPause();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(ClipDescription.MIMETYPE_TEXT_PLAIN);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("Check your mime type.");
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
private void handleIntent(Intent intent){
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
String type = intent.getType();
if (ClipDescription.MIMETYPE_TEXT_PLAIN.equals(type)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
new NdefReaderTask().execute(tag);
} else {
Log.d(TAG, "Wrong mime type: " + type);
}
} else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// In case we would still use the Tech Discovered Intent
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
String searchedTech = Ndef.class.getName();
for (String tech : techList) {
if (searchedTech.equals(tech)) {
new NdefReaderTask().execute(tag);
break;
}
}
}
}
}
and this is my ClassesAttendenceActivity
package com.melin.vustudentattendence;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipDescription;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class ClassAttendenceActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ClassAttendenceRowAdapter adapter;
private List<Student> students=new ArrayList<>();
private FirebaseFirestore fs;
private String incomingIntentData;
private NfcAdapter mNfcAdapter;
private static String TAG="Attendence Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_attendence);
//check nfc first
mNfcAdapter=NfcAdapter.getDefaultAdapter(this);
if(mNfcAdapter==null){
Toast.makeText(this,"This device doesn't support NFC",Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mNfcAdapter.isEnabled()){
Toast.makeText(this,"NFC is disabled.Please enable it",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "NFC is in reader mode", Toast.LENGTH_SHORT).show();
}
//incomingIntentData=getIntent().getExtras().getString("document");
//fs=FirebaseFirestore.getInstance();
//Toast.makeText(this,incomingIntentData,Toast.LENGTH_LONG).show();
//recyclerView=(RecyclerView)findViewById(R.id.attendenceListRecyclerView);
// LinearLayoutManager layoutManager=new LinearLayoutManager(ClassAttendenceActivity.this);
// recyclerView.setLayoutManager(layoutManager);
// populateStudentList(incomingIntentData);
handleIntent(getIntent());
}
private void populateStudentList(String url){
fs.collection(url+"/students")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Map<String,Object> data=document.getData();
Student student=new Student();
student.setStatus("ABSENT");
for (Map.Entry<String,Object> entry : data.entrySet()){
if(entry.getKey().equals("name")){
student.setName(entry.getValue().toString());
}
if(entry.getKey().equals("student_id")){
student.setStudent_id(entry.getValue().toString());
}
}
students.add(student);
Log.d("List", document.getId() + " => " + document.getData());
}
} else {
Log.d("List", "Error getting documents: ", task.getException());
}
adapter=new ClassAttendenceRowAdapter(students);
recyclerView.setAdapter(adapter);
}
});
}
public void simulatingAnIntent(){
String student_id="101";
for(Student student:students){
if(student.getStudent_id().equals(student_id)){
student.setStatus("PRESENT");
Toast.makeText(ClassAttendenceActivity.this,"Student ID"+student.getStudent_id()+"Detected",Toast.LENGTH_LONG).show();
}
}
adapter=new ClassAttendenceRowAdapter(students);
recyclerView.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
setupForegroundDispatch(this, mNfcAdapter);
}
#Override
protected void onPause() {
stopForegroundDispatch(this,mNfcAdapter);
super.onPause();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(ClipDescription.MIMETYPE_TEXT_PLAIN);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("Check your mime type.");
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
private void handleIntent(Intent intent){
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
String type = intent.getType();
if (ClipDescription.MIMETYPE_TEXT_PLAIN.equals(type)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
new NdefReaderTask().execute(tag);
} else {
Log.d(TAG, "Wrong mime type: " + type);
}
} else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// In case we would still use the Tech Discovered Intent
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
String searchedTech = Ndef.class.getName();
for (String tech : techList) {
if (searchedTech.equals(tech)) {
new NdefReaderTask().execute(tag);
break;
}
}
}
}
public class NdefReaderTask extends AsyncTask<Tag,Void,String> {
#Override
protected String doInBackground(Tag... params) {
Tag tag = params[0];
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// NDEF is not supported by this Tag.
return null;
}
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord ndefRecord : records) {
if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported Encoding", e);
}
}
}
return null;
}
private String readText(NdefRecord record) throws UnsupportedEncodingException {
/*
* See NFC forum specification for "Text Record Type Definition" at 3.2.1
*
* http://www.nfc-forum.org/specs/
*
* bit_7 defines encoding
* bit_6 reserved for future use, must be 0
* bit_5..0 length of IANA language code
*/
byte[] payload = record.getPayload();
// Get the Text Encoding
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
// Get the Language Code
int languageCodeLength = payload[0] & 0063;
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
// e.g. "en"
// Get the Text
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(ClassAttendenceActivity.this,"Student ID"+result+"Detected",Toast.LENGTH_LONG).show();
// for(Student student:students){
// if(student.getStudent_id().equals(result)){
// student.setStatus("PRESENT");
// Toast.makeText(ClassAttendenceActivity.this,"Student ID"+student.getStudent_id()+"Detected",Toast.LENGTH_LONG).show();
// }
// }
//
// adapter=new ClassAttendenceRowAdapter(students);
// recyclerView.setAdapter(adapter);
}
}
}
}
As you can see both the activities are almost identical
while one reads the data another doesn't
It turns out that using emulated nfc tag was the error.Using real nfc tag worked well.Though no one answered the question I am answering my own question so that when someone encounters this problem they can see this answer.Thank you.
I searched the web for examples displaying pdf documents within a app. Additionally i searched for a Downloader class because i want to load the pdf from the internet. After execution it just displays blank PDF page.
MainActivity.java just sends the pdf link to the DisplayPDF.java Activity:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.pdfviewevaluation.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DisplayPDF.class);
String url = "pdf link";
intent.putExtra(EXTRA_MESSAGE, url);
startActivity(intent);
}
}
DisplayPDF.java creates the Folder and PDF in the cache directory. Then it starts the Downloader with the pdf link and directory. Finally it should just show the pdf:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class DisplayPDF extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pdf);
String pdfURL = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
File folder = new File(this.getCacheDir(), "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader dl = new Downloader(pdfURL, file);
try {
dl.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
showPdf();
}
public void showPdf() {
File file = new File(this.getCacheDir()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(this.getApplicationContext(), this.getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
Downloader.java connects to the pdf page and download the pdf from the given link to the desired directory:
package com.example.pdfviewevaluation;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Downloader extends AsyncTask<Void,Void,Void> {
private String fileURL;
private File directory;
public Downloader(String fileURL, File directory)
{
this.fileURL = fileURL;
this.directory = directory;
}
protected Void doInBackground(Void... params) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int i = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
After many hours spending on my problem i searched for another solution on YouTube. These one are showing the solution:
https://www.youtube.com/watch?v=pGlqHeB5hdk
https://www.youtube.com/watch?v=8YPJCOxiklQ
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadingfiles">
<uses-sdk android:minSdkVersion="21"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
</application>
</manifest>
MainActivity.java:
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String myUrl = "http://www.orimi.com/pdf-test.pdf";
private ImageView imageView;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myUrl));
request.setTitle("File download.");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
render();
}
};
/**Called when the user clicks the "Next" button defined in activity_main.xml */
public void nextPage(View view) {
currentPage++;
render();
}
/**Called when the user clicks the "Previous" button defined in activity_main.xml */
public void previousPage(View view) {
currentPage--;
render();
}
private void render(){
try{
imageView = (ImageView) findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
File file = new File("/sdcard/Download/"+nameOfFile);
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0){
currentPage = 0;
}else if(currentPage >= renderer.getPageCount()){
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (Exception e){
e.printStackTrace();
}
}
}
I have a problem with my Android client/server app. I would like to connect devices by WiFi Direct and send through some media files.
I made an Activity and Service for both Client and Server. Code is below.
ServerActivity:
import java.util.ArrayList;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ServerActivity extends Activity {
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiServerReceiver;
private IntentFilter wifiServerReceiverIntentFilter;
private WifiP2pConfig config;
private String deviceName;
private Intent intent;
PeerListListener myPeerListListener;
ArrayList<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
WifiP2pDeviceList peerList;
TextView text;
EditText et2;
Button button1;
ListView listView;
ArrayAdapter<String> BTArrayAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(BTArrayAdapter);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiServerReceiverIntentFilter = new IntentFilter();
;
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiServerReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
intent = null;
registerReceiver(wifiServerReceiver, wifiServerReceiverIntentFilter);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
wifiManager.discoverPeers(wifichannel, null);
wifiManager.requestPeers(wifichannel, new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
peers.clear();
peers.addAll(peerList.getDeviceList());
}
});
for (int i = 0; i < peers.size(); i++) {
WifiP2pDevice device = peers.get(i);
deviceName = device.deviceName;
config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifiManager.connect(wifichannel, config, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(
getApplicationContext(),
"Połączono z: " + deviceName + "\n Mac: "
+ config.deviceAddress, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Nie udało się połączyć",
Toast.LENGTH_SHORT).show();
}
});
}
wifiManager.requestConnectionInfo(wifichannel,
new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
// TODO Auto-generated method stub
String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
Toast.makeText(getApplicationContext(),
"GroupOwnAddress: " + groupOwnerAddress, Toast.LENGTH_SHORT)
.show();
}
});
StartServer(null);
}
});
}
public void StartServer(View v) {
// Construct our Intent specifying the Service
intent = new Intent(this, ServerService.class);
startService(intent);
}
}
ServerService:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
public class ServerService extends IntentService {
Handler mHandler;
private int port = 2178;
ServerSocket welcomeSocket = null;
Socket socket = null;
public ServerService() {
super("ServerService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
try {
mHandler.post(new DisplayToast(this, "Creating ServerSocket.."));
welcomeSocket = new ServerSocket(port);
welcomeSocket.setReuseAddress(true);
mHandler.post(new DisplayToast(this, "Waiting for connection on port: "
+ welcomeSocket.getLocalPort()));
socket = welcomeSocket.accept();
// while(true && flag){
// socket = welcomeSocket.accept();
mHandler.post(new DisplayToast(this, "Coneccted!"));
// }
mHandler.post(new DisplayToast(this, "Succes!"));
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "IOException"));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "Exception"));
}
mHandler.post(new DisplayToast(this, "ServerService"));
}
/*
public void onDestroy() {
try {
welcomeSocket.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast2 implements Runnable {
private final Context mContext;
String mText;
public DisplayToast2(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
ClientActivity:
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class ClientActivity extends Activity {
Button button;
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiClientReceiver;
private IntentFilter wifiClientReceiverIntentFilter;
private WifiP2pInfo wifiInfo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiClientReceiver = new WiFiClientBroadcastReceiver(wifiManager, wifichannel, this);
wifiClientReceiverIntentFilter = new IntentFilter();
;
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiClientReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
wifiInfo = null;
registerReceiver(wifiClientReceiver, wifiClientReceiverIntentFilter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
StartClient(null);
}
});
}
public void setNetworkToReadyState(boolean status, WifiP2pInfo info, WifiP2pDevice device) {
wifiInfo = info;
// targetDevice = device;
// connectedAndReadyToSendFile = status;
}
public void StartClient(View v) {
Intent intent = new Intent(this, ClientService.class);
intent.putExtra("wifiInfo", wifiInfo);
if (wifiInfo == null) {
Toast.makeText(this, "WifiInfo = null!", Toast.LENGTH_SHORT).show();
}
startService(intent);
}
}
ClientService:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.Handler;
import android.widget.Toast;
public class ClientService extends IntentService {
Handler mHandler;
private WifiP2pInfo wifiInfo;
private int port = 2178;
Socket clientSocket = null;
OutputStream os = null;
public ClientService() {
super("ClientService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
wifiInfo = (WifiP2pInfo) intent.getExtras().get("wifiInfo");
InetAddress targetIP = wifiInfo.groupOwnerAddress;
clientSocket = new Socket();
if(wifiInfo.isGroupOwner)
{
try {
mHandler.post(new DisplayToast(this, "Try to connect: /N IP: " + targetIP + "/nPort: " +port));
clientSocket.connect(new InetSocketAddress(targetIP, port));
mHandler.post(new DisplayToast(this, "Connected!"));
//os = clientSocket.getOutputStream();
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "serwer IOException: " + e.getMessage()));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "serwer Exception"));
}
}else{
mHandler.post(new DisplayToast(this, "Group owner = " + wifiInfo.isGroupOwner));
}
}
/*
public void onDestroy()
{
try {
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast implements Runnable {
private final Context mContext;
String mText;
public DisplayToast(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".AppModeSelection"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ServerService"
android:exported="false" />
<service
android:name=".ClientService"
android:exported="false" />
<activity android:name=".ServerActivity" >
</activity>
<activity android:name=".ClientActivity" >
</activity>
</application>
</manifest>
I am using two phones with WiFi Direct (Samsung GT-I9505 Android 4.4.2 and Samsung GT-I8190N Adroid 4.1.2). First of all I turned off all connections (BT, WIFI) and then connected by WiFi Direct. GT-I9505 is Server and other one is Client. While establishing a connection IOException error appears:
IOException: failed to connect to /192.168.49.1 (port 2178): connect failed: ECONNREFUSED (Connection refused)
I tried to use plenty of others Pors but nothing works. What I did wrong?
Thank you in advance for any help!
UPDATE:
I noticed that when I disconnect WiFi direct and connect again but in other direction it works but only for moment.
the main issue with your code is that you do need to make it event driven, in the current state I'm surprised that it even does anything really.
So, please try making it to something like following:
1. Start Discovering peers, once you get Peers Changed event, then do requestPeers
2. if you need some listener etc. to be ready for you on the other side, then you likely would identify those devices by advertising a service, so next look start discovery for services.
3. After you get service discovered, start 5-second timer to wait for any additional, reset the timer after each service discovered, and once the timer finally gets to run uninterrupted 5 seconds, you likely have discovered all services available at that time.
4. Select ONE service and connect to that device (you can not have multiple connection really).
5. Once you get event that you are connected, then use requestConnectionInfo to get info for the connection.
Then do remember that before you start you need to create the local service, so the other side can see it. Then, if your device gets selected as Group owner, you could keep the advertisement on, and let more clients connect to you. But if you are selected as Client, then you can not have incoming connections, so you should get rid of the advertisement.
I'm developing a app at the moment wich displayes a Map, your gps postition and a marker on this postition. Next Step is to recieve Data from a XML file. The XML I'm trying to use is http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4
But poorly after launching the app (on a real device, newest version) the app terminates and displays nothing.
LogCat says FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xmlparser/com.example.xmlparser.MainActivitz}: java.lang.nullPointerException
MainActivity.java
package com.example.xmlparser;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public String url = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4";
public EditText feldname, id;
public HandleXml obj;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
feldname = (EditText)findViewById(R.id.editText1);
id = (EditText)findViewById(R.id.editText2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
float lat1 = (float) (location.getLatitude()); //Getting the position
float lng1 = (float) (location.getLongitude());
GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title("Your Position"));
LatLng bounds = new LatLng(lat1, lng1);
CameraUpdate cu = CameraUpdateFactory.newLatLng(bounds);
mMap.moveCamera(cu);
}
//Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
float lat = (float) (location.getLatitude()); //Getting the ' ''
float lng = (float) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void open(View view)
{
feldname.setText(url);
obj = new HandleXml(url);
obj.fetchXML();
while(obj.parsingComplete);
feldname.setText(obj.getFeldName());
id.setText(obj.getId());
}
}
HandleXml.java
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class HandleXml {
private String feldname = "name";
private String id = "id";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXml(String url)
{
this.urlString = url;
}
public String getFeldName()
{
return feldname;
}
public String getId()
{
return id;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
try
{
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("name_kana"))
{
feldname = text;
}
else if(name.equals("id"))
{
id =text;// myParser.getAttributeValue(null,"value");
}
else
{}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlparser"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="18" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:debuggable="true">
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.example.xmlparser.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyC3DipaFNo1EC44rZ8N1AJKVAiUCNOtqZw"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I really hope one of you can tell me whats wrong with this code as it was working perfectly fine with only the map on it's own and the parser as an own program.