Android version7 returns null URI.
My Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myautochatapp.sampleapp">
<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.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".VideoActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="#string/file_provider_authority"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
String set in the manifest
<string name="file_provider_authority" translatable="false">com.myautochatapp.sampleapp.fileprovider</string>
MainActivity
public class VideoActivity extends AppCompatActivity {
Button capture_video;
TextView path_text;
private Uri fileUri;
final int MEDIA_CAPTURE_VIDEO=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
capture_video= (Button) findViewById(R.id.capture_video);
path_text= (TextView) findViewById(R.id.path_text);
capture_video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callVideoCapFuc();
}
});
}
private void callVideoCapFuc() {
File vfile= null;
String dateTimeOrg= new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date()).toString();
try {
vfile = createTemporaryFile("VID_"+dateTimeOrg,".mp4");
} catch (Exception e) {
e.printStackTrace();
}
fileUri = FileProvider.getUriForFile(VideoActivity.this,
getString(R.string.file_provider_authority),
vfile);
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takeVideoIntent, MEDIA_CAPTURE_VIDEO);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case MEDIA_CAPTURE_VIDEO:
Uri videoUri = null;
try {
videoUri = data.getData();
}catch (Exception e){
e.printStackTrace();
}
if (videoUri.toString()!=null && !videoUri.toString().equalsIgnoreCase("")){
path_text.setText(videoUri.toString());
}
break;
}
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/Mine/");
if(!tempDir.exists())
{
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
}
Provider Path provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files" path="." />
</paths>
XML layout activity_video
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myautochatapp.sampleapp.VideoActivity">
<Button
android:layout_width="match_parent"
android:id="#+id/capture_video"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:id="#+id/path_text"
android:layout_below="#+id/capture_video"
android:layout_height="wrap_content" />
</RelativeLayout>
Note given permission in the code but set when launching the application, but still, it is not working, it returns null onActivityResult() if it's Android 7. In Android 6 working fine
put these line in the onCreate() method in your activity or in onCreateView() method in your fragment.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Related
How can I start an activity when my app is in background? I mean, when it has not been destroyed? I have tried with IntentService and nothing, I just want to make a StartActivity to launch my MainActivity in the background.
Your service needs to be a foreground service.
Here is how.
First in your Manifest.xml file.
Request for permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
......
<!-- Your Service-->
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.FOREGROUND_SERVICE"/>
Start your service with:
startForegroundService(Intent(this, MyService::class.java))
Then in your service display the foreground notification(usually in the onStartCommand):
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val ncCompat = NotificationChannelCompat.Builder("your.own.id.here", NotificationManagerCompat.IMPORTANCE_DEFAULT).setName("Important").build()
NotificationManagerCompat.from(baseContext).createNotificationChannel(ncCompat)
startForeground("your.notification.id.goes.here".hashCode(), NotificationCompat.Builder(baseContext, nmCompat.id).setContentTitle("My Foreground Service").setContentText("Running Service").build())
return super.onStartCommand(intent, flags, startId)
}
Then your can start an activity(for example: see below)
val intent = Intent(application, MainActivity2::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
intent.addFlags(Intent.FLAG_FROM_BACKGROUND)
startActivity(intent)
Android may complain that your activity needs to inherit theme from Theme.AppCompat and you may also have difficulties loading an xml layout.
I believe your can work around those. Apart from that your are good to go.
And also note that i only tested it on Android 10 and below.
Right-click on the project, Select New >> Service >> Service and add the following to MyServices.java
public class MyService extends Service {
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
onTaskRemoved(intent);
Toast.makeText(getApplicationContext(),"This is a Service running in Background",
Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:text="Click here"
android:textStyle="bold"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Add the following code to src/MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
}
}
Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<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">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<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>
Let's try to run your application.
Click on the Click here button to start background services.
I am developing an Application for Android devices and I wanted to scan QR codes, but I have one problem, it just wont ask for the Camera permission, therefore the surfaceview just stays black.
My Code:
public class ScanQR extends AppCompatActivity {
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextView textView;
private BarcodeDetector barcodeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr);
surfaceView = (SurfaceView) findViewById(R.id.scanQR);
textView = (TextView) findViewById(R.id.tvScanQr);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this, barcodeDetector).setRequestedPreviewSize(640, 480).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
} try {
cameraSource.start(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size() > 0){
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
}
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.estcers.partygooo">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<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" />
<activity android:name=".Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CreateParty" />
<activity android:name=".SearchUser" />
<activity android:name=".UserInfo" />
<activity android:name=".Friends" />
<activity android:name=".PendingFriends" />
<activity android:name=".Parties" />
<activity android:name=".Invitations" />
<activity android:name=".Entries" />
<activity android:name=".PendingAssistances" />
<activity android:name=".PartyInfo" />
<activity android:name=".GetQR" />
<meta-data
android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="barcode" />
<activity android:name=".ScanQR"></activity>
</application>
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ScanQR"
android:orientation="vertical">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="300sp"
android:id="#+id/scanQR"
android:layout_gravity="center"
android:layout_marginTop="100sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvScanQr"
android:text="AAAAAAAAAAAAAAAA"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_marginTop="20sp"
android:gravity="center"/>
If anyone could help me with this problem I would be really grateful, I just have no clue of what is going on.
I also have the implementation:
"implementation 'com.google.android.gms:play-services-vision:15.0.2'" and google().
Thanks for any help!
When you're about to open the camera, include the following check:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(YourCameraActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
and handle the result with:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(CameraActivity.this, "The app requires that permission in order to work properly!", Toast.LENGTH_LONG).show();
finish();
}
}
}
and in your manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In my activity_main.XML file I have three main parts,
1) ActionBar(ToolBar) - Its in the top,
2) FrameLayout - in the middle,
3) BottomBar(ToolBar).
Now in FrameLayout I want to add and replace fragment based upon the button selection made in bottom toolbar. In my first fragment I am having google map and in my 2nd and 3rd fragment I am having ListView. I also adding the fragment in the backstack by adding this while replacing/adding fragment
ft.addToBackStack(null);
Now the problem is, whenever I open each fragment by clicking the bottom bar buttons all the fragment are working fine completely. But if I open 2nd or 3rd fragment from 1st(Google Map) fragment, and If I again try to comeback to the same Google Map fragment by clicking the back button Its showing these errors in Logcat.
Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f0e00d9, tag null, or parent id 0xffffffff wi
09-16 16:46:29.112 6985-6985/com.imnv.im026.goodmorning E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.imnv.im026.goodmorning, PID: 6985
android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
........................ com.imnv.im026.goodmorning.FragmentLocate.onCreateView(FragmentLocate.java:64)
And my map fragment xml file is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical">
<fragment
android:id="#+id/locateDriverMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/locateCallIconLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<include
android:id="#+id/includedCallIcon"
layout="#layout/locate_frament_bottom_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Any my map fragment class is...
public class FragmentLocate extends Fragment {
private PrefManager pref;
ur="example.com/---";
private GoogleMap mMap;
Activity mActivity;
private View view;
private String userId, driverId;
private static double latitude1, longitude1;
android.support.v4.app.FragmentManager fragmentManager;
GetDriverForCustomer getDriverId;
public FragmentLocate() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_locate, container, false);
getDriverId = new GetDriverForCustomer(getActivity());
driverId = getDriverId.getDriverProfileDetails();
pref = new PrefManager(getActivity());
userId = pref.getKeyUserid();
getDriverGeoLocation();
mMap = ((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
return view;
}
#Override
public void onStart() {
super.onStart();
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(loc).icon(null).title("Your Location"));
if (mMap != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude1, longitude1)).title("Driver Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.car_marker)));
LatLng coordinate = new LatLng(latitude1, longitude1);
CameraUpdate DriverLocation = CameraUpdateFactory
.newLatLngZoom(coordinate, 12);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(DriverLocation);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(coordinate)
.zoom(17)
.build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
/*#Override
public void onResume() {
super.onResume();
*//*setUpMapIfNeeded();
if (mMap == null) {
mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}*//*
}*/
public void getDriverGeoLocation() {
/*driverId = pref.getKeyDriverid();
Log.d("driverId", driverId);*/
String fullUrl = locateURL + driverId;
Log.d("PrintFullURL", fullUrl);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
fullUrl, null, new Response.Listener<JSONObject>() {
private String jsonResponse = "";
#Override
public void onResponse(JSONObject response) {
Log.d("Activity Car Profile ", response.toString());
try {
JSONArray jcarArray = response.getJSONArray("getdriverlocation");
for (int i = 0; i < jcarArray.length(); i++) {
JSONObject driverLocation = jcarArray.getJSONObject(i);
latitude1 = Double.parseDouble(driverLocation.getString("latitude"));
longitude1 = Double.parseDouble(driverLocation.getString("longitude"));
Log.e("latitude & longitude", latitude1 + " " + longitude1);
}
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude1, longitude1)).title("Marker").icon(BitmapDescriptorFactory.fromResource(R.drawable.car_marker)));
LatLng coordinate = new LatLng(latitude1, longitude1);
CameraUpdate DriverLocation = CameraUpdateFactory
.newLatLngZoom(coordinate, 12);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(DriverLocation);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(coordinate)
.zoom(17)
.build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Activity Car Profile", "Error: " + error.toString());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
}
And My Manifestfile is...
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" />
<application
android:name=".app.AppController"
android:allowBackup="true"
android:icon="#mipmap/gm_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:uiOptions="splitActionBarWhenNarrow">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<meta-data
android:name="android.support.UI_OPTIONS"
android:value="splitActionBarWhenNarrow" />
<activity
android:name=".ViewPagerScreen"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:label="string/login_bt" />
<activity
android:name=".DriverShiftActivity"
android:label="#string/title_activity_driver_shift"
android:uiOptions="splitActionBarWhenNarrow">
<meta-data
android:name="android.support.UI_OPTIONS"
android:value="splitActionBarWhenNarrow" />
</activity>
<activity
android:name=".BaseMenuActivity"
android:label="#string/title_activity_base_menu"
android:uiOptions="splitActionBarWhenNarrow">
<meta-data
android:name="android.support.UI_OPTIONS"
android:value="splitActionBarWhenNarrow" />
</activity>
<activity
android:name=".SignUp"
android:label="#string/title_activity_sign_up" />
<activity
android:name=".DiaglogBoxShiftDriver"
android:label="#string/title_activity_diaglog_box_shift_driver"
android:theme="#android:style/Theme.Dialog" />
<activity
android:name=".FuelDetails"
android:label="#string/title_activity_fuel_details" />
<activity
android:name=".MyProfile"
android:label="#string/title_activity_my_profile" />
<activity
android:name=".CarProfile"
android:label="#string/title_activity_car_profile" />
<activity
android:name=".CustomerProfile"
android:label="#string/title_activity_customer_profile" />
<activity
android:name=".ChatTimeLine"
android:label="#string/title_activity_chat_time_line" />
<activity
android:name=".CustomerActivity"
android:label="#string/title_activity_customer"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerEnquiryActivity"
android:label="#string/title_activity_customer_enquiry"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerEmergencyActivity"
android:label="#string/title_activity_customer_emergency"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerMyProfile"
android:label="#string/title_activity_customer_my_profile"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerDriverProfile"
android:label="#string/title_activity_customer_driver_profile"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerPlaceInDetail"
android:label="#string/title_activity_customer_place_in_detail"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerSelectedCategory"
android:label="#string/title_activity_customer_selected_category"
android:theme="#style/MyMaterialTheme" />
<activity
android:name=".CustomerChangePassword"
android:label="#string/title_activity_customer_forget_password"
android:theme="#style/MyMaterialTheme" />
</application>
</manifest>
And I am repeating its showing error only when I try to comeback to the fragment by clicking back button. Thank you.
try this code in oncreat
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.map, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return view;
I am developing an Android app consisting of two activites so far. The first activity (MainActivity) is started when the app is launched or when a QR code is scanned. The MainActivity starts the second activity (NFCActivity) when the user presses a button. The NFCActivity waits for the user to tap a NFC token, reads out data from the token, and returns the read data to the MainActivity.
This works fine if the app is started manually. If the app is started by scanning a QR code, taping the NFC tag does not invoke the NFCActivity's onNewIntent() method as exepcted, but instead creates a new instance of the NFCActivity on top of the already displayed one.
The enableForegroundDispatch() method is called and FLAG_ACTIVITY_SINGLE_TOP should be set. Relevant source code of a minimal example is provided below. Any help would be highly appreciated!
MainActivity:
public class MainActivity extends Activity {
private EditText dataRead;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
dataRead = (EditText) findViewById(R.id.data);
final Button readKeyButton = (Button) findViewById(R.id.readNFC);
readKeyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent keyIntent = new Intent(MainActivity.this,
NFCActivity.class);
keyIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(keyIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 1) {
String result = intent.getExtras().getString("resultData");
this.dataRead.setText(result);
}
}
}
Main Activity's GUI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/readNFC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="127dp"
android:text="Read NFC Tag" />
<EditText
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/readNFC"
android:layout_centerHorizontal="true"
android:layout_marginBottom="85dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
NFCActivity:
public class NFCActivity extends Activity {
private NfcAdapter mAdapter;
private PendingIntent pendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_nfc);
mAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// // Setup an intent filter for all MIME based dispatches
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mFilters = new IntentFilter[] { ndef, td };
//
// // Setup a tech list for all NfcF tags
mTechLists = new String[][] { new String[] { NfcV.class.getName(),
NfcF.class.getName(), NfcA.class.getName(),
NfcB.class.getName() } };
}
#Override
public void onResume() {
super.onResume();
if (mAdapter != null)
mAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
mTechLists);
}
#Override
public void onPause() {
super.onPause();
if (mAdapter != null)
mAdapter.disableForegroundDispatch(this);
}
#Override
public void onNewIntent(Intent intent) {
Log.d("TEST", "onNewIntent() called.");
// READ THE NFC TAG HERE [SKIPPED FOR MINIMAL EXAMPLE]
// Return dummy data for test
Intent result = new Intent();
result.putExtra("resultData", "DUMMY DATA");
setResult(1, result);
finish();
}
}
NFCActivity's GUI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#303030"
android:paddingLeft="30dp"
android:paddingRight="30dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Tap your NFC tag.."
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8811"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.nfcqrtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="test.nfcqrtest.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="test.org" android:pathPrefix="/testapp" />
</intent-filter>
</activity>
<activity
android:name=".NFCActivity"
android:windowSoftInputMode="stateHidden" android:screenOrientation="portrait" android:launchMode="singleTop">
</activity>
</application>
</manifest>
In case somebody is facing a similar problem: I was finally able to overcome the issue described above by setting the android:launchMode property for the MainActivity to singleInstance.
I am developing an Android application which uses Google maps for android v2. The problem i having is that when i run it using the AVD in Eclipse i recieve no authentication error in the log cat output.
I am now testing my application on an Android tablet (nexus 7 2013) and i recieve this error when executing the application:
12-12 01:09:13.968: E/Google Maps Android API(14759): Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
12-12 01:09:13.968: E/Google Maps Android API(14759): Ensure that the following correspond to what is in the API Console: Package Name: dcs.aber.ac.uk.cs211.group02, API Key: AIzaSyDcnzt6cdjEbCXSCRSTezmUHbaPW679if8, Certificate Fingerprint: 52FDB9ABBBAA062226834E35BF6A39FA2A3E27A7
I have tried to regen the API key, the one in the logcat matches the one provided in the google API console.
I have tried a clean project/clean install on the device several times, still no luck. The reast of the application works fine, only the map does not.
Here is my manifest.xml al the permissions seem ok.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dcs.aber.ac.uk.cs211.group02"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<permission
android:name="dcs.aber.ac.uk.cs211.group02.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Accessing camera hardware -->
<!-- putting android.hardware.camera prevents non-camera devices using this app -->
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="dcs.aber.ac.uk.cs211.group02.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:logo="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<uses-library
android:name="com.google.android.maps"
android:required="true" />
<activity
android:name="dcs.aber.ac.uk.cs211.group02.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.CreateWalkActivity"
android:label="#string/title_activity_create_walk" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.HelpScreen"
android:label="#string/title_activity_help_screen" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.WalkRecording"
android:label="#string/title_activity_walk_recording" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.CreateNewPOIActivity"
android:label="#string/title_activity_create_new_poi" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDcnzt6cdjEbCXSCRSTezmUHbaPW679if8" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="dcs.aber.ac.uk.cs211.group02.ConfrimUploadActivity"
android:label="#string/title_activity_confrim_upload" >
</activity>
<activity
android:name="dcs.aber.ac.uk.cs211.group02.ServerResponse"
android:label="#string/title_activity_server_response" >
</activity>
</application>
</manifest>
This is the xml where the map is located:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".WalkRecording" >
<fragment
android:id="#+id/mapView"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="400dp" />
<ImageButton
android:id="#+id/walkRecordingHelpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="16dp"
android:background="#color/transparent"
android:contentDescription="#string/helpIconAltText"
android:src="#drawable/help" />
<Button
android:id="#+id/walkRecordingNewPOIButton"
style="#android:style/TextAppearance.Small"
android:layout_width="85dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/mapView"
android:layout_marginBottom="8dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="8dp"
android:text="#string/walkRecordingNewPOIButtonText"
android:textColor="#color/light_gray" />
<Button
android:id="#+id/walkRecordingUploadButton"
style="#android:style/TextAppearance.Small"
android:layout_width="85dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/walkRecordingNewPOIButton"
android:layout_alignBottom="#+id/walkRecordingNewPOIButton"
android:layout_alignParentRight="true"
android:layout_marginBottom="8dp"
android:layout_marginRight="15dp"
android:layout_marginTop="8dp"
android:text="#string/walkRecordingUploadButtonText"
android:textColor="#color/light_gray" />
</RelativeLayout>
And the code:
package dcs.aber.ac.uk.cs211.group02;
import java.util.Vector;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class WalkRecording extends FragmentActivity {
private static String walkName, walkSDesc, walkLdesc;
private GoogleMap map;
private Context context;
private Button newPOIButton, uploadButton;
private ImageButton helpButton;
private static Vector<PointOfInterest> pois = new Vector<PointOfInterest>();
private CreateNewPOIActivity POIAct;
private final static int NEW_POI_REQ = 0;
private final static int EDIT_WALK_DETAILS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walk_recording);
context = this;
Bundle bundle = getIntent().getBundleExtra("Walk info");
if(bundle != null){
walkName = bundle.getString("walkTitle");
walkSDesc = bundle.getString("walkSdesc");
walkLdesc = bundle.getString("walkLDesc");
}
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView)).getMap();
map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(52.4140,4.0810) , 14.0f));
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
POIAct = new CreateNewPOIActivity();
addOnClickListeners();
}
public void addOnClickListeners(){
helpButton = (ImageButton) findViewById(R.id.walkRecordingHelpButton);
helpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, HelpScreen.class);
startActivity(intent);
}
});
newPOIButton = (Button) findViewById(R.id.walkRecordingNewPOIButton);
newPOIButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CreateNewPOIActivity.class);
startActivityForResult(intent, NEW_POI_REQ);
}
});
uploadButton = (Button) findViewById(R.id.walkRecordingUploadButton);
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
Intent intent = new Intent(context, ConfrimUploadActivity.class);
Bundle b = new Bundle();
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.walk_recording, menu);
return true;
}
public void uploadTosever() {
}
public void deleteWalk() {
}
public double getLongitude() {
return 0;
}
public double getLattitude() {
return 0;
}
public static Vector<PointOfInterest> getPois() {
return pois;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == NEW_POI_REQ){
if( resultCode == RESULT_OK ) {
PointOfInterest p = data.getExtras().getParcelable("POIObject");
Toast lol = Toast.makeText(context, p.getName(), Toast.LENGTH_LONG);
lol.show();
pois.add(p);
Toast x = Toast.makeText(context, "POIS SIZE " + pois.size() , Toast.LENGTH_LONG);
x.show();
}
}
else if(requestCode == EDIT_WALK_DETAILS){
if( resultCode == RESULT_OK ) {
}
}
}
public static String getWalkName() {
return walkName;
}
public static void setWalkName(String walkName) {
WalkRecording.walkName = walkName;
}
public static String getWalkSDesc() {
return walkSDesc;
}
public static void setWalkSDesc(String walkSDesc) {
WalkRecording.walkSDesc = walkSDesc;
}
public static String getWalkLdesc() {
return walkLdesc;
}
public static void setWalkLdesc(String walkLdesc) {
WalkRecording.walkLdesc = walkLdesc;
}
}
Any ideas?
Resolved. alls it took was a device reset...