parsing error after launching intent to install apk - java

So i have a function which downloads and then installs the apk. When the intent launches I get "There was a problem parsing this package." error. However,if i try installing it manually it works fine.
DownloadActivity.java:
public void onClickUpdate(View view) throws IOException {
Toast.makeText(SettingsActivity.this, "Checking for updates", Toast.LENGTH_SHORT).show();
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10,TimeUnit.SECONDS).readTimeout(10,TimeUnit.SECONDS).build();
final Request request=new Request.Builder().url("theurl").addHeader("version",version).get().build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try {
File sdcard=new File("sdcard/Download");
File file=new File(sdcard,"app-debug.apk");
file.createNewFile();
BufferedSink sink=Okio.buffer(Okio.sink(file));
sink.writeAll(Objects.requireNonNull(response.body()).source());
sink.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SettingsActivity.this, "Installed successfully!", Toast.LENGTH_LONG).show();
try{
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri=Uri.parse("content://"+"sdcard/Download/app-debug.apk");
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);}catch (Exception e){
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}finally {
response.close();
}
}
});
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.testapp.test">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="false"
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=".VersionActivity">
</activity>
<activity android:name=".SettingsActivity">
</activity>
<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>
Also I did try Android install apk programmatically error - Package Parse error but that did not help at all.
the logs:
2020-09-29 07:31:13.669 24595-29726/? E/ActivityThread: Failed to find provider info for sdcard
2020-09-29 07:31:13.671 24595-29726/? W/InstallStaging: Error staging apk from content URI
java.io.FileNotFoundException: No content provider: content://sdcard/Download/app-debug.apk
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1506)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1357)
at android.content.ContentResolver.openInputStream(ContentResolver.java:1071)
at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:167)
at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:161)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

I fixed it by adding this:
StrictMode.VmPolicy.Builder builder=new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure;
I don't recommend doing this.
Try wrapping your file URI with content:// instead.

Related

stoped android pdf view When you restart the phone

I am trying to open pdf files in this code with a library barteksc
I save a link as a URI in database Then I fetch and open the link in a library barteksc
The code works fine, the problem is when I restart the phone the PDF file is not opened It appears that the error in
load pdf error
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.downloads.DownloadStorageProvider from ProcessRecord{f6420b9 6172:com.azizlabiod.librarypdfpro/u0a218} (pid=6172, uid=10218) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
code java
final int KITKAT_VALUE =1002;
Intent intent;
intent = new Intent();
if (Build.VERSION.SDK_INT < 19){
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
intent.setType("application/pdf");
try {
startActivityForResult(intent, KITKAT_VALUE);
} catch (ActivityNotFoundException e) {
//alert user that file manager not working
Toast.makeText(getApplicationContext(), R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == 1002
&& resultCode == Activity.RESULT_OK) {
Uri uri ;
if (resultData != null) {
uri=resultData.getData();
String name= getFileName(uri);
db.insertRowAdmins(name,uri.toString(),R.drawable.book,23, db.getNameTableId().get(positionTab));
setNotify();
}
}
}
code manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.LibraryPDFPro"
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShowBook"
android:exported="false" />
<activity
android:name=".ShowDiatel"
android:exported="false" />
</application>
</manifest>
probleme
/PDFView: load pdf error
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.downloads.DownloadStorageProvider from ProcessRecord{f6420b9 6172:com.azizlabiod.librarypdfpro/u0a218} (pid=6172, uid=10218) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:3776)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5034)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2044)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1517)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1121)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:958)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:811)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:765)
at com.github.barteksc.pdfviewer.source.UriSource.createDocument(UriSource.java:37)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:53)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:27)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Remove:
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
And, in your onActivityResult(), if the request was for ACTION_OPEN_DOCUMENT, call takePersistableUriPermissions() on a ContentResolver. That's how you get durable access to the content, and without that you lose access after a short while.

File provider used in sending email attachment keeps crashing

I am trying to send an email upon button click with an attachment stored in internal storage. I tried following this tutorial in implementing a file provider, however every time I try running the app and pressing the button the app crashes and stops working.
I am lost for why that may be. Below is the relevant code:
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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">
<provider
android:name="android.support.v4.content.FileProvider"
android:grantUriPermissions="true"
android:exported="false"
android:authorities="${applicationId}">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths"/>
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<cache-path name="cache" path="/" />
<files-path name= "files" path="/" />
</paths>
</PreferenceScreen>
MainActivity.java
Button emailBtn = (Button) findViewById(R.id.button);
main = findViewById(R.id.main);//email form button
emailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = Screenshot.takescreenshotOfRootView(main);
ImageView programLogo = (ImageView) findViewById(R.id.imageView);
programLogo.setImageBitmap(b);
File filePath = new File(loadImageFromStorage(saveToInternalStorage(b)), "profile.jpg");
Intent intent = new Intent(Intent.ACTION_SEND, Uri.fromParts(
"mailto","myemail#gmail.com", null));
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = (Uri) FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, filePath);
intent.setDataAndType(uri, "application/jpg");
String subject = "please work";
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});
}
private String saveToInternalStorage(Bitmap bitmapImage) {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
private String loadImageFromStorage(String path) {
File f = new File(path, "profile.jpg");
return f.getAbsolutePath();
}
This is the error I get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication234567, PID: 5272
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.myapplication234567/app_imageDir/profile.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:418)
at com.example.myapplication234567.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:6913)
at android.view.View.performClickInternal(View.java:6890)
at android.view.View.access$3200(View.java:792)
at android.view.View$PerformClick.run(View.java:27158)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
Your message contains this path which appears incorrect: /data/data/com.example.myapplication234567/app_imageDir/profile.jpg/profile.jpg
try catches are your friend.

is == null while getting xml file from internet

I have the following situation: I need to get xml file from the Internet and then get lyrics from this file. Here's the url of this xml. Here's the code, which I wrote and which should do it.
private static class NetworkLyricsDownload extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=Eminem&song=Lose%20Yourself");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(getInputStream(url), "UTF-8");
boolean insideItem = false;
int eventType = xmlPullParser.getEventType();
while (eventType!=XmlPullParser.END_DOCUMENT){
if (eventType == XmlPullParser.START_TAG){
if (xmlPullParser.getName().equalsIgnoreCase("lyric")){
insideItem = true;
Log.i(getClass().getName(), xmlPullParser.nextText());
}
}
eventType = xmlPullParser.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private InputStream getInputStream(URL url){
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
But when I run the app, I have the following error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: asus.example.com.player, PID: 14458
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.IllegalArgumentException: is == null
at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1636)
at asus.example.com.player.UploadLyricsActivity$NetworkLyricsDownload.doInBackground(UploadLyricsActivity.java:114)
at asus.example.com.player.UploadLyricsActivity$NetworkLyricsDownload.doInBackground(UploadLyricsActivity.java:86)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
I have permission in manifest file ( <uses-permission android:name="android.permission.INTERNET"/>
) but it still doesn't help. So, what's the matter and how can I solve it?
UPD
Here's my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="asus.example.com.player"
android:targetSandboxVersion="1">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<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"
android:networkSecurityConfig="#xml/network_security_config"
android:usesCleartextTraffic="true"
tools:ignore="AllowBackup,GoogleAppIndexingWarning,UnusedAttribute">
<activity android:name=".SongLyricsActivity"/>
<activity android:name=".UploadLyricsActivity" />
<activity
android:name=".ListOfSongsActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedService" />
</application>
</manifest>

Why Messages not received from gcm

I tried to register my device into GCM service.
that's worked, I get register id of my device and store that on my server.
but when I send message to my device nothing affected and device can not recive message.
Response on google at send message:
{u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8319562714448073760L, u'results': [{u'message_id': u'0:1445751667241995%f044e3acf9fd7ecd'}]}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.ac.buqaen.rc"
android:versionCode="5"
android:versionName="1.4">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.VIBRATE"/>
<permission
android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="ir.ac.buqaen.rc.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:name=".network.AppController"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:theme="#style/Theme.Main"
android:allowBackup="true">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".gcm.MessageActivity"/>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="ir.ac.buqaen.rc" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
ServerUtilities.java
public final class ServerUtilities {
private static final String TAG = "GCM";
public static void register(final Context context, final String regId){
final MySharedPreferences sp = new MySharedPreferences(context);
long teacher_id = sp.sharedPreferences.getLong("teacher_id", -1);
TeacherHelper teacherHelper = new TeacherHelper(context);
teacherHelper.teacher = teacherHelper.findById(teacher_id);
Map<String, String> params = new HashMap<String, String>();
Log.d("regid", "---- regId:" + regId);
params.put("reg_id", regId);
params.put("name", teacherHelper.teacher.getStringName());
params.put("email", teacherHelper.teacher.getStringEmail());
params.put("user_id", teacherHelper.teacher.getStringUsername());
params.put("device_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
CustomRequest request = new CustomRequest(context, Globals.UrlGCMRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
try {
int vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
if (data.getBoolean("status")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
sp.saveToPreferences("gcm_reg_id", regId);
GCMRegistrar.setRegisteredOnServer(context, true);
} else if (data.getString("msg").equals("already registered")) {
sp.saveToPreferences("gcm" + vc, data.getJSONObject("value").getString("id"));
GCMRegistrar.setRegisteredOnServer(context, true);
sp.saveToPreferences("gcm_reg_id", regId);
} else {
Log.e(TAG, "registering device failed");
}
} catch (JSONException e) {
Log.e("Response Error _ " + context.getClass().getSimpleName(), "----" + e.getMessage());
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
/**
* Unregister this account/device pair within the server.
*/
public static void unregister(final Context context, final String regId) {
final MySharedPreferences sp = new MySharedPreferences(context);
Map<String, String> params = new HashMap<String, String>();
params.put("reg_id", regId);
CustomRequest request = new CustomRequest(context, Globals.UrlGCMUnRegister, params, new CustomRequest.ResponseAction() {
#Override
public void onResponseAction(JSONObject data) throws JSONException {
if (data.getBoolean("status")) {
int vc = 1;
try {
vc = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
sp.editor.remove("gcm" + vc);
sp.editor.remove("gcm_reg_id");
sp.editor.commit();
GCMRegistrar.setRegisteredOnServer(context, false);
}
}
});
AppController.getInstance().addToRequestQueue(request, "request gcm");
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(Globals.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
ServerUtilities.register(context, registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
ServerUtilities.unregister(context, registrationId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("tes", "~~~" + intent.getExtras());
Log.i(TAG, "Received message");
MessageHelper messageHelper = new MessageHelper(context);
try {
JSONObject data = new JSONObject(intent.getExtras().getString("message"));
messageHelper.message = new Message(
null, data.getInt("type"), data.getInt("status"), data.getString("content"),
data.getString("title"), data.getString("date")
);
messageHelper.Save();
createNotification(context, messageHelper.message);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
private void createNotification(Context context, Message message) {
Intent notificationIntent;
notificationIntent = new Intent(this, Message.class);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationIntent.putExtra("message_id", message.id);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, message.id.intValue(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.bu_logo)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bu_logo))
.setTicker(getString(R.string.new_message))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://ir.ac.buqaen.rc/raw/notification"))
.setContentTitle(message.title)
.setContentText(message.getContentText(context));
Notification notification = builder.build();
notificationManager.notify(message.id.intValue(), notification);
}
}
MainActivity
try {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(getApplicationContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(getApplicationContext());
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(getApplicationContext());
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(getApplicationContext(), Globals.SENDER_ID);
} else {
// Try to register again if device is not registered on GCM
if (!GCMRegistrar.isRegisteredOnServer(getApplicationContext())) {
ServerUtilities.register(getApplicationContext(), regId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I dont khow why this code not worked! I use this code in another project and get messages on my app, but this code in this application on receive messages.
Can problem from my package name? :)
ir.ac.buqaen.rc
Please help me hoe to fix this problem.
According to Set up a GCM Client App on Android
For existing apps that extend a WakefulBroadcastReceiver, Google
recommends migrating to GCMReceiver and GcmListenerService. To
migrate:
In the app manifest, replace your GcmBroadcastReceiver with "com.google.android.gms.gcm.GcmReceiver", and replace the current
service declaration that extends IntentService to the new
GcmListenerService
Remove the BroadcastReceiver implementation from your client code
Refactor the current IntentService service implementation to use GcmListenerService
Then, you can refer to my following manifest file. Hope this helps!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gcmclient" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service android:name=".service.GcmService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name=".service.LoggingService" android:exported="false" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:clearTaskOnLaunch="false"
android:finishOnTaskLaunch="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Cannot create folder in SD card on Android

I have this problem in my application. I want to create a folder in Emulator SD card but it didn't work and I don't know why. I tried mkdir and mkdirs.
I added WRITE_EXTERNAL_STORAGE Permission to the Manifest. I tried with MediaScannerConnection and didn't work. I've searched a lot the web and tried a lot of implementations but no change. What could be the issue?
Here is my code:
public void createDirIfNotExists() {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cdp");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Log.e("Folder: ", "folder created!!");
} else {
Log.e("Folder Error: ", "folder cannot be created!!");
}
}
My manifest look like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aboussof.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".Test">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And so I try to create the folder:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(Test.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(Test.this);
createDirIfNotExists();
downloadTask.execute("http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
Replace
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cdp");
with
File folder = new File(Environment.getExternalStorageDirectory() + "/", "cdp");
Have you solved your issue yet?
I use your method with a tiny change at
File folder = new File(Environment.getExternalStorageDirectory(), "cdp");
And the result like the following screenshot:
My AVD configuration like the following:
I have had the same issue - file.mkdirs() returns false on android emulator API 23. And all configs was set according to BNK's answer.
Try to change API to 19 - it works for me. Looks like weird emulator/android version issue.

Categories

Resources