Device is registering but problem in getting notification, I tried in many ways but not succeeded. please anyone help me on this.
Below is my GCMIntentService.java
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package in.oneindia.android.clickin;
import static in.oneindia.android.clickin.utils.CommonUtilities.displayMessage;
import in.oneindia.android.clickin.LeftAndRightActivity;
import in.oneindia.android.clickin.MailActivity;
import in.oneindia.android.clickin.R;
import in.oneindia.android.clickin.HomeActivity;
import in.oneindia.android.clickin.SplashScreenActivity;
import in.oneindia.android.clickin.utils.CommonUtilities;
import in.oneindia.android.clickin.utils.ServerUtilities;
import in.oneindia.android.clickin.utils.SharedPrefUtils;
import in.oneindia.android.clickin.utils.Util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService()
{
super(CommonUtilities.SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
Util.logv(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered));
ServerUtilities.register(context, registrationId);
String strId = registrationId;
//Log.v("","CHECKING GCM WORKING OR NOT:::::::"+strId);
if (strId != null) {
SharedPrefUtils.setPushID(context, strId);
//this.saveRegistrationIdAndSendToServer(strId);
}
}
public String saveRegistrationIdAndSendToServer(String registrationId)
{
String strRegistrationId=null;
Util.logv("C2DM", "Sending registration ID to my application server");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://rss.oneindia.in/apps/registerId.php?action="+registrationId);
try
{
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null)
{
strRegistrationId= line;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return strRegistrationId;
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Util.logv(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
if (GCMRegistrar.isRegisteredOnServer(context)) {
ServerUtilities.unregister(context, registrationId);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Util.logv(TAG, "Ignoring unregister callback");
}
}
#Override
protected void onMessage(Context context, Intent intent) {
Util.logv(TAG, "Received message");
String action = intent.getAction();
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
String myTitle = intent.getStringExtra("classifiedTitle");
String myPostID = intent.getStringExtra("postID");
String myImage = intent.getStringExtra("classifiedImage");
//String csFlashNews = intent.getStringExtra("flash_news");
//String csShowAd = intent.getStringExtra("show_ad");
//String csFlashContent = intent.getStringExtra("flash_content");
Util.logv(TAG, "TITLE : "+myTitle);
Util.logv("MyPOSTID", "POST ID : "+myPostID);
String s=myTitle.toString();
parse_json_add(s);
displayMessage(context, myTitle);
// notifies user
generateNotification(context, myTitle, myPostID, myImage);
}
}
private void parse_json_add(String text) {
if (text!= null)
{
try {
JSONObject temp=new JSONObject(text);
String value=temp.get("state").toString();
Log.v(TAG, value);
} catch (Exception e) {
// TODO: handle exception
}
}
}
#Override
protected void onDeletedMessages(Context context, int total) {
Util.logv(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
String entryID = null;
String URL = null;
/*String flashNews = null;
String showAd = null;
String flashContent = null;*/
// notifies user
generateNotification(context, message, entryID, URL);
}
#Override
public void onError(Context context, String errorId) {
Util.logv(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Util.logv(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
public static void generateNotification(Context context, String message, String EntryID, String src) {
//String title = context.getString(R.string.app_name);
String title = "Click.in";
//String URL = "http://tamil.oneindia.in/img/2014/05/25-kejriwal113434-600.jpg";
Bitmap largeIcon = getBitmapFromUrl(src);
if(largeIcon == null)
{
largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.clickinicon512x512);
}
try
{
double ArticleEntryID = 0;
int csbooleanFlashNews = 0;
int csbooleanShowAd = 0;
if(EntryID != null && !EntryID.equals(""))
{
ArticleEntryID = Double.parseDouble(EntryID);
}
/*if(strBooleanFlashNews != null && !strBooleanFlashNews.equals(""))
{
csbooleanFlashNews = Integer.parseInt(strBooleanFlashNews);
}
if(strBooleanShowAd != null && !strBooleanShowAd.equals(""))
{
csbooleanShowAd = Integer.parseInt(strBooleanShowAd);
}*/
Intent notificationIntent;
if(ArticleEntryID == 0)
{
notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.putExtra("checkingpush", "PUSH");
/*notificationIntent.putExtra("showad", csbooleanShowAd);
notificationIntent.putExtra("flashnews", csbooleanFlashNews);
notificationIntent.putExtra("flashnewscontent", csFlashContent);
notificationIntent.putExtra("selectedposition", 0);
notificationIntent.putExtra("channelid", 0);*/
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
else
{
notificationIntent = new Intent(context, LeftAndRightActivity.class);
notificationIntent.putExtra("pushdata", EntryID);
notificationIntent.putExtra("title", csbooleanShowAd);
//notificationIntent.putExtra("flashnews", csbooleanFlashNews);
notificationIntent.putExtra("checkingpush", "PUSH");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
/*// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);*/
PendingIntent intent =
PendingIntent.getActivity(context, new Random(System.currentTimeMillis()).nextInt(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
int id = sp.getInt("notifid", -1);
id++;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
{
// Using RemoteViews to bind custom layouts into Notification
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.notification_layout_normal);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.clickinicon512x512)
.setTicker(message)
.setAutoCancel(true)
.setContentIntent(intent)
.setContent(remoteViews);
//remoteViews.setImageViewBitmap(R.id.notification_imageview, largeIcon);
//remoteViews.setTextViewText(R.id.notification_text_title, message);
//remoteViews.setImageViewBitmap(R.id.notification_title_imageview, buildUpdate(context, message, SharedPrefUtils.getLanguage(context)));
Notification n = builder.build();
n.contentView = remoteViews;
n.defaults = Notification.DEFAULT_SOUND;
NotificationManager notificationmanager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
notificationmanager.notify(id, n);
}else
{
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
android.support.v4.app.NotificationCompat.Builder builder = new android.support.v4.app.NotificationCompat.Builder(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
in.oneindia.android.clickin.R.layout.notification_layout_expandable);
remoteViews.setImageViewBitmap(R.id.notification_imageview, largeIcon);
remoteViews.setTextViewText(R.id.notification_text_title, message);
remoteViews.setTextViewText(R.id.notification_text_appname, title);
builder.setContentIntent(intent)
.setTicker(message)
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setLargeIcon(Bitmap.createScaledBitmap(largeIcon, 100, 100, false))
.setContentText(message)
.setSmallIcon(R.drawable.clickinicon512x512);
//.setAutoCancel(true);
Notification n = builder.build();
/*if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
{
n.bigContentView = remoteViews;
}*/
n.flags = Notification.FLAG_AUTO_CANCEL;
n.defaults = Notification.DEFAULT_SOUND;
nm.notify(id, n);
}
if ( id > 10){ // Overwrite notification 10 notification is very long list
sp.edit().remove("notifid").commit(); //async
} else {
sp.edit().putInt("notifid",id).commit();
}
}catch(Exception e)
{
}
}
public static Bitmap getBitmapFromUrl(String src)
{
URL url = null;
InputStream input = null;
HttpURLConnection connection = null;
try {
url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
public static Bitmap buildUpdate(Context context, String txt, String lang)
{
int bmapwidth = 320;
int bmapheight = 60;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int csWidth = dm.widthPixels;
float density = context.getResources().getDisplayMetrics().density;
float txtsize = 14;
float csLineSpaceAdd = 1f;
float csLineSpaceMul = 1f;
if(csWidth <=240)
{
bmapwidth = 220;
bmapheight = 55;
}else if(csWidth > 240 && csWidth <= 320)
{
bmapwidth = 280;
bmapheight = 60;
}else if(csWidth > 320 && csWidth <= 600)
{
bmapwidth = 350;
}else if (csWidth > 600) {
bmapwidth = 400;
}
String language = lang;
if (language.equals("6"))
{
if(density <= 0.75)
{
txtsize = 20;
}
else if(density > 0.75 && density <= 1)
{
txtsize = 17;
}
else if(density > 1 && density < 2)
{
txtsize=14;
}
else if(density >= 2)
{
txtsize=13;
}
}else if (language.equals("7"))
{
if(density <= 0.75)
{
txtsize = 18;
}
else if(density > 0.75 && density < 2)
{
txtsize=15;
}
else if(density >= 2)
{
txtsize=13;
}
}
else {
if(density <= 0.75)
{
txtsize = 17;
}
else if(density > 0.75 && density < 2)
{
txtsize=14;
}
else if(density >= 2)
{
txtsize=13;
}
}
String title_txt = txt;
Typeface langFont = null;
Bitmap myBitmap = Bitmap.createBitmap(bmapwidth, bmapheight, Bitmap.Config.ARGB_8888);
//Bitmap myBitmap = null;
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Log.v("languageSelected : ", language);
Log.v("Title : ", ""+txt);
if (language.equals("2")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/hindi.ttf");
csLineSpaceAdd = -1.8f;
csLineSpaceMul = 0.8f;
}else if (language.equals("3")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/kannada.ttf");
csLineSpaceAdd = -0.8f;
}else if (language.equals("4")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/telugu.ttf");
csLineSpaceAdd = -0.8f;
}else if (language.equals("5")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/malayalam.ttf");
csLineSpaceAdd = -0.7f;
}else if (language.equals("6")) {
//title_txt = TamilUtil.convertToTamil(TamilUtil.BAMINI, txt, context);
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/Bamini.ttf");
}else if (language.equals("7")) {
langFont = Typeface.createFromAsset(context.getAssets(),"fonts/lohit_gu.ttf");
csLineSpaceAdd = 0.5f;
}
//Log.v("typeface : ", ""+langFont);
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(langFont);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
TextView csText=new TextView(context);
csText.setTextColor(context.getResources().getColor(R.color.white));
csText.setTypeface(langFont);
csText.setGravity(Gravity.CENTER_VERTICAL);
csText.setText(title_txt);
csText.setTextSize(txtsize);
csText.setEllipsize(TextUtils.TruncateAt.END);
csText.setLines(2);
csText.setLineSpacing(csLineSpaceAdd, csLineSpaceMul);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(bmapwidth, bmapheight);
csText.setLayoutParams(lp);
csText.setDrawingCacheEnabled(true);
csText.measure(MeasureSpec.makeMeasureSpec(myCanvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(myCanvas.getHeight(), MeasureSpec.EXACTLY));
csText.layout(0, 0, csText.getMeasuredWidth(), csText.getMeasuredHeight());
myCanvas.drawBitmap(csText.getDrawingCache(), 0, 0, paint);
csText.setDrawingCacheEnabled(false);
return myBitmap;
}
public static void cancelAllNotification(Context context) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
Below are permissions which I gave in Manifest.xml. Please help me on this
<permission
android:name="in.oneindia.android.clickin.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="in.oneindia.android.clickin.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<service android:name="in.oneindia.android.clickin.GCMIntentService" />
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
enter code here
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="in.oneindia.android.clickin" />
</intent-filter>
</receiver>
Related
I use broadcastreceiver of media folder android.hardware.action.NEW_PICTURE service to rename and move image using this code and it was running:
CameraReciver
package perim.ebrahimi.ir.perim;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
public class CameraReciver extends BroadcastReceiver {
private States states;
private SessionManager session;
private WriteService main;
#Override
public void onReceive(Context context, Intent intent) {
getStates(context);
if(states.getAPP()){
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
if(cursor!=null){
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
main = new WriteService();
main.writeFolder(image_path, states, context);
}
cursor.close();
} else abortBroadcast();
}
// OK
private void getStates(Context context){
session = new SessionManager(context.getApplicationContext());
states = new States();
states = session.getSession();
}
}
and here is WriteService:
package perim.ebrahimi.ir.perim;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WriteService extends Activity {
private States states;
private Context context;
private static CalendarJalalian cal;
private static int day ;
private static int month ;
private static int year ;
private static int saat ;
private static int minut ;
private static int secnd ;
private int orientation = -1;
private static final int REQUEST_EXTERNAL_STORAGE = 100;
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS=200;
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// //setContentView(R.layout.activity_main);
//
// // A simple check of whether runtime permissions need to be managed
// if (Build.VERSION.SDK_INT >= 23) {
// checkMultiplePermissions();
// }
// }
public void writeFolder(String image_path, States _states, Context _context){
states = _states;
context= _context;
cal = new CalendarJalalian();
long fileSize = new File(image_path).length();
Cursor mediaCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + ">=?",
new String[]{String.valueOf(cal.getTimeInMillis()/1000 - 1)},
MediaStore.MediaColumns.DATE_ADDED + " desc");
if (mediaCursor != null && mediaCursor.getCount() !=0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
if(size == fileSize){
orientation = mediaCursor.getInt(0);
break;
}
}
}
orientation = (orientation<0)?0:orientation;
image_path = changeName(image_path);
if(image_path.length()==0) return;
String image_jadid = copyFile(image_path);
if(states.getMain() && image_jadid.length()>0){
removeMain(image_path);
removeMedia(context, new File(image_path));
}
if(states.getPayam()) Toast.makeText(this, getText(R.string.imageSaved)+": "+states.getKhas(), 500).show();
}
private void checkExternalStorage(){
String[] aaa = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, aaa , REQUEST_EXTERNAL_STORAGE);
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
}
private static void removeMedia(Context context, File f) {
ContentResolver resolver = context.getContentResolver();
resolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[] { f.getAbsolutePath() });
}
// OK
private String changeName(String image_path){
String result = "";
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
File from = new File(image_path);
if(from.exists()){
if(states.getOnimage()){
addTextToImage(image_path, persianDateName);
}
File to = new File(from.getParentFile(),persianDateName);
try
{
boolean b = from.renameTo(to);
if (!b) {
copy(from, to);
from.delete();
}
removeMedia(context, from);
sendToMedia(to, persianDateName);
result = to.getAbsolutePath();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return result;
}
private void addTextToImage(String from, String persianDateName) {
Log.i("info","Draw "+persianDateName+" on image");
try
{
Log.i("info","1");
FileOutputStream fos = new FileOutputStream(from);
if(fos==null) Log.i("info","fos = null");
Log.i("info","2 = "+from);
Bitmap bitmap = BitmapFactory.decodeFile(from);
if(bitmap==null) Log.i("info","bitmap = null");
// Log.i("info","3");
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig==null) Log.i("info","bitmapConfig = null");
// Log.i("info","4");
// if (bitmapConfig == null) {
// bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
// }
Log.i("info","5");
bitmap = bitmap.copy(bitmapConfig, true);
Log.i("info","6");
Canvas canvas = new Canvas(bitmap);
Log.i("info","7");
Resources resources = this.getResources();
float scale = resources.getDisplayMetrics().density;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(61, 61, 61));
paint.setTextSize((int) (14 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect qab = new Rect();
paint.getTextBounds(persianDateName, 0, persianDateName.length(), qab);
int x = (bitmap.getWidth() - qab.width()) / 2;
int y = (bitmap.getHeight() + qab.height()) / 2;
canvas.drawText(persianDateName, x, y, paint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.i("info","Text added on image");
}
private void copy(final File f1, final File f2) throws IOException {
if(f2.exists()) f2.delete();
//checkExternalStorage();
checkMultiplePermissions();
if(mExternalStorageAvailable && mExternalStorageWriteable) {
f2.createNewFile();
final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
file1.close();
file2.close();
}
}
private boolean canRename(final File f1, final File f2) {
final String p1 = f1.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
final String p2 = f2.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
return p1.replaceAll("\\/\\w+", "").equals(p2.replaceAll("\\/\\w+", ""));
}
// OK
private void removeMain(String image_path){
File f = new File(image_path);
if(f.exists()) f.delete();
}
// OK
private File createFileName(){
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
String masirFolder = "";
if(states.getSal()) masirFolder += year;
if(states.getMah()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month);
if(states.getRuz()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day);
if(states.getSaat()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat);
if(states.getMinut()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat)+"_"+((minut<10)?"0"+minut:minut);
if(states.getKhas().length()>0) masirFolder += File.separator+states.getKhas();
File directTime = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), masirFolder);
if (!directTime.mkdir()) makeDir(directTime);
directTime = new File(directTime, persianDateName);
return directTime;
}
// OK
private void makeDir(File direct){
direct.mkdirs();
}
// OK
private String copyFile(String image_path){
String masir = "";
File sourceFile = new File(image_path);
if (!sourceFile.exists()) {return masir;}
File destinationFile = createFileName();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
masir = destinationFile.getName();
sendToMedia(destinationFile, masir);
masir = destinationFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return masir;
}
// OK
private void sendToMedia(File imageFile, String imageTitle){
ContentValues image = new ContentValues();
Date dateTaken = new Date();
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(MediaStore.Images.Media.TITLE, imageTitle);
image.put(MediaStore.Images.Media.DISPLAY_NAME, String.format(this.getText(R.string.imageDisplayName).toString(),states.getKhas()));
image.put(MediaStore.Images.Media.DESCRIPTION, String.format(this.getText(R.string.imageDescription).toString(),name));
image.put(MediaStore.Images.Media.DATE_ADDED, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_MODIFIED, dateTaken.toString());
image.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
image.put(MediaStore.Images.Media.ORIENTATION, orientation);//getImageOrientation(imageFile.getAbsolutePath()));
image.put(MediaStore.Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(MediaStore.Images.Media.SIZE, imageFile.length());
image.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
}
private void checkMultiplePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissionsNeeded = new ArrayList<String>();
List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
permissionsNeeded.add("GPS");
}
if (!addPermission(permissionsList, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
permissionsNeeded.add("Read Storage");
}
if (permissionsList.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
try {
if (Build.VERSION.SDK_INT >= 23)
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
} catch(Exception ex){
ex.printStackTrace();
}
return true;
}
}
But class addPermission raise error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.content.Context.checkSelfPermission(java.lang.String)' on a
null object reference
I think the way I call activity is not correct, but I have no idea how to do it, please help.
Edit:
I have found this difference in returned path:
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
The changed part is obvious:
old but correct path: /storage/emulated/0/DCIM/Camera/IMG_20161215_173334.jpg
new but incorrect path: /storage/3466-033/DCIM/Camera/IMG_20161215_173334.jpg
I think since new devices permit user to select where to save Images, then returning address is changed accordingly.
How to get correct address out of cursor?
You can't do that with a broadcast receiver. You can check if you have a permission via ContextCompat.checkSelfPermission, but in order to request the permission, you need to call ActivityCompat.requestPermissions. It needs an activity, and the result will also arrive to that activity.
Given that, the best solution for you is to implement some activity which will explain the user what is going on and request the permission. If the broadcast receiver detects that it doesn't have the necessary permission, it would launch this activity. When the permission is granted, the normal operation would be resumed.
I have to say that as a user it would be very weird to me if a dialog with a permission request suddenly popped up out of the blue, so I think it's for the best that you need to have an activity to request permissions.
Judging by your path, however, it is definitely somewhere on the SD card. This means that the SD card write restrictions apply. That means that requesting permissions for writing won't help. Take a look at this question: How to avoid the “EACCES permission denied” on SD card?
I trying to change chatroom.java's createReplayMsg message resource from GCM ,but why apapter.getData().add error?
It tell me java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference.
maybe I should use AsyncTask to finish it?
PS. I am first use this forum ,other Resources in this-> https://github.com/yyting/yoyotrip or tell me,thanks.
Logcat:
09-17 16:42:14.410 8416-8416/com.example.yoyotrip E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.yoyotrip, PID: 8416
java.lang.RuntimeException: Unable to start receiver com.example.yoyotrip.GCM.GcmBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2586)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.yoyotrip.chat.MessageAdapter.getData()' on a null object reference
at com.example.yoyotrip.GCM.GcmBroadcastReceiver.onReceive(GcmBroadcastReceiver.java:63)
chatroom.java
package com.example.yoyotrip;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.example.yoyotrip.chat.MessageInputToolBox;
import com.example.yoyotrip.chat.OnOperationListener;
import com.example.yoyotrip.chat.Option;
public class chatroom extends ActionBarActivity {
private MessageInputToolBox box;
public ListView listView;
public MessageAdapter adapter;
public List<Message> messages ;
#SuppressLint("UseSparseArrays")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
initMessageInputToolBox();
initListView();
}
/**
* init MessageInputToolBox
*/
#SuppressLint("ShowToast")
public void initMessageInputToolBox(){
box = (MessageInputToolBox) findViewById(R.id.messageInputToolBox);
box.setOnOperationListener(new OnOperationListener() {
#Override
public void send(String content) {
System.out.println("===============" + content);
int rd=(int)(Math.random()*99)+1;
Message message = new Message(0, 1, rd%2==1?"Tom":"helen", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFace(String content) {
System.out.println("===============" + content);
Message message = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Tomcat", "avatar", "Jerry", "avatar", content, true, true, new Date());
adapter.getData().add(message);
listView.setSelection(listView.getBottom());
//Just demo
createReplayMsg(message);
}
#Override
public void selectedFuncation(int index) {
System.out.println("===============" + index);
switch (index) {
case 0:
//do some thing
break;
case 1:
//do some thing
break;
default:
break;
}
Toast.makeText(chatroom.this, "Do some thing here, index :" +index, Toast.LENGTH_LONG).show();
}
});
ArrayList<String> faceNameList = new ArrayList<String>();
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
for(int x = 1; x <= 10; x++){
faceNameList.add("big"+x);
}
ArrayList<String> faceNameList1 = new ArrayList<String>();
for(int x = 1; x <= 7; x++){
faceNameList1.add("cig"+x);
}
ArrayList<String> faceNameList2 = new ArrayList<String>();
for(int x = 1; x <= 24; x++){
faceNameList2.add("dig"+x);
}
Map<Integer, ArrayList<String>> faceData = new HashMap<>();
faceData.put(R.drawable.em_cate_magic, faceNameList2);
faceData.put(R.drawable.em_cate_rib, faceNameList1);
faceData.put(R.drawable.em_cate_duck, faceNameList);
box.setFaceData(faceData);
List<Option> functionData = new ArrayList<Option>();
for(int x = 0; x < 5; x++){
Option takePhotoOption = new Option(this, "Take", R.drawable.take_photo);
Option galleryOption = new Option(this, "Gallery", R.drawable.gallery);
functionData.add(galleryOption);
functionData.add(takePhotoOption);
}
box.setFunctionData(functionData);
}
private void initListView(){
listView = (ListView) findViewById(R.id.messageListview);
//create Data
Message message = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hi,大家好我是你們的導遊", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 8));
Message message1 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "Hello", false ,true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)* 8));
Message message2 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "helen", "avatar", "Jerry", "avatar", "我們要在哪集合??", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message3 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Tom", "avatar", "Jerry", "avatar", "台北車站嗎!?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 7));
Message message4 = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "big3", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
Message message5 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS, "Joe", "avatar", "Jerry", "avatar", "可以在229公園那邊嗎?", false, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message6 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_FAIL, "Tom", "avatar", "Jerry", "avatar", "test send fail", true, false, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
// Message message7 = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SENDING, "Tom", "avatar", "Jerry", "avatar", "test sending", true, true, new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24) * 6));
messages = new ArrayList<Message>();
messages.add(message);
messages.add(message1);
messages.add(message2);
messages.add(message3);
messages.add(message4);
messages.add(message5);
// messages.add(message6);
// messages.add(message7);
adapter = new MessageAdapter(this, messages);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
box.hide();
return false;
}
});
}
//change message resource from GCM
public void createReplayMsg(final Message message){
final Message reMessage = new Message(message.getType(), 1, message.getFromUserName(), "avatar", "Jerry", "avatar",
message.getType() == 0 ? "Re:" + message.getContent() : message.getContent(),
false, true, new Date()
);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000 * (new Random().nextInt(3) +1));
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.getData().add(reMessage);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
MessageAdapter.java
package com.example.yoyotrip.chat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.example.yoyotrip.R;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;
public class MessageAdapter extends BaseAdapter {
private Context context;
private List<Message> data = null;
public MessageAdapter(Context context, List<Message> list) {
super();
this.context = context;
this.data = list;
}
#Override
public int getCount() {
return data != null ? data.size() : 0;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return this.data.get(position).getIsSend() ? 1 : 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
final Message message = data.get(position);
boolean isSend = message.getIsSend();
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
if (isSend) {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_right, null);
} else {
convertView = LayoutInflater.from(context).inflate(R.layout.msg_item_left, null);
}
viewHolder.sendDateTextView = (TextView) convertView.findViewById(R.id.sendDateTextView);
viewHolder.sendTimeTextView = (TextView) convertView.findViewById(R.id.sendTimeTextView);
viewHolder.userAvatarImageView = (ImageView) convertView.findViewById(R.id.userAvatarImageView);
viewHolder.userNameTextView = (TextView) convertView.findViewById(R.id.userNameTextView);
viewHolder.textTextView = (TextView) convertView.findViewById(R.id.textTextView);
viewHolder.photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
viewHolder.faceImageView = (ImageView) convertView.findViewById(R.id.faceImageView);
viewHolder.failImageView = (ImageView) convertView.findViewById(R.id.failImageView);
viewHolder.sendingProgressBar = (ProgressBar) convertView.findViewById(R.id.sendingProgressBar);
viewHolder.isSend = isSend;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
String dateString = DateFormat.format("yyyy-MM-dd h:mmaa", message.getTime()).toString();
String[] t = dateString.split(" ");
viewHolder.sendDateTextView.setText(t[0]);
viewHolder.sendTimeTextView.setText(t[1]);
if(position == 0){
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}else{
//TODO is same day ?
Message pmsg = data.get(position-1);
if(inSameDay(pmsg.getTime(), message.getTime())){
viewHolder.sendDateTextView.setVisibility(View.GONE);
}else{
viewHolder.sendDateTextView.setVisibility(View.VISIBLE);
}
}
} catch (Exception e) {
}
viewHolder.userNameTextView.setText(message.getFromUserName());
switch (message.getType()) {
case 0://text
viewHolder.textTextView.setText(message.getContent());
viewHolder.textTextView.setVisibility(View.VISIBLE);
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.textTextView);
if( message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
viewHolder.sendingProgressBar.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.textTextView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 1://photo
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.photoImageView.setVisibility(View.VISIBLE);
viewHolder.faceImageView.setVisibility(View.GONE);
//TODO set image
int id = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.photoImageView.setImageResource(id);
if(message.getIsSend() ){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.photoImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.photoImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
case 2://face
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.textTextView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.VISIBLE);
int resId = context.getResources().getIdentifier(message.getContent(), "drawable", context.getPackageName());
viewHolder.faceImageView.setImageResource(resId);
if(message.getIsSend()){
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
LayoutParams layoutParams = (LayoutParams) viewHolder.failImageView.getLayoutParams();
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.faceImageView);
if(message.getSendSucces() != null && message.getSendSucces() == false){
viewHolder.failImageView.setVisibility(View.VISIBLE);
viewHolder.failImageView.setLayoutParams(layoutParams);
}else{
viewHolder.failImageView.setVisibility(View.GONE);
}
if(message.getState() != null && message.getState() == 0){
viewHolder.sendingProgressBar.setVisibility(View.VISIBLE);
viewHolder.sendingProgressBar.setLayoutParams(layoutParams);
}else{
viewHolder.sendingProgressBar.setVisibility(View.GONE);
}
}else{
viewHolder.failImageView.setVisibility(View.GONE);
LayoutParams sendTimeTextViewLayoutParams = (LayoutParams) viewHolder.sendTimeTextView.getLayoutParams();
sendTimeTextViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.faceImageView);
viewHolder.sendTimeTextView.setLayoutParams(sendTimeTextViewLayoutParams);
}
break;
default:
viewHolder.textTextView.setText(message.getContent());
viewHolder.photoImageView.setVisibility(View.GONE);
viewHolder.faceImageView.setVisibility(View.GONE);
break;
}
// viewHolder.textTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
return convertView;
}
public List<Message> getData() {
return data;
}
public void setData(List<Message> data) {
this.data = data;
}
public static boolean inSameDay(Date date1, Date Date2) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int year1 = calendar.get(Calendar.YEAR);
int day1 = calendar.get(Calendar.DAY_OF_YEAR);
calendar.setTime(Date2);
int year2 = calendar.get(Calendar.YEAR);
int day2 = calendar.get(Calendar.DAY_OF_YEAR);
if ((year1 == year2) && (day1 == day2)) {
return true;
}
return false;
}
static class ViewHolder {
public ImageView userAvatarImageView;
public TextView sendDateTextView;
public TextView userNameTextView;
public TextView textTextView;
public ImageView photoImageView;
public ImageView faceImageView;
public ImageView failImageView;
public TextView sendTimeTextView;
public ProgressBar sendingProgressBar;
public boolean isSend = true;
}
}
GcmBroadcastReceiver.java
package com.example.yoyotrip.GCM;
/**
* Created by colm on 2015/8/3.
*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.ListView;
import com.example.yoyotrip.MainActivity;
import com.example.yoyotrip.R;
import com.example.yoyotrip.chat.Message;
import com.example.yoyotrip.chat.MessageAdapter;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.util.Date;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
public static final int NOTIFICATION_ID = 0;
public ListView listView;
public MessageAdapter adapter;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
Log.i(getClass() + " GCM ERROR", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
Log.i(getClass() + " GCM DELETE", extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
Log.i(getClass() + " GCM MESSAGE", extras.toString());
if (extras.getString("title") .equals("chat")) {
/*show noteic*/
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "noteic", extras
.getString("message"), extras.getString("whofrom"), false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
//message addchat
final Message message = new Message(0, 1, extras.getString("whofrom"), "avatar", "Jerry", "avatar", extras.getString("message"), false, true, new Date());
adapter.getData().add(message);
adapter.notifyDataSetChanged();
listView.setSelection(listView.getBottom());
} else if (extras.getString("title").equals("GCM")) {
Intent i = new Intent(context, MainActivity.class);
i.setAction("android.intent.action.MAIN");
i.addCategory("android.intent.category.LAUNCHER");
MagicLenGCM.sendLocalNotification(context, NOTIFICATION_ID,
R.drawable.icon, "GCM noteic", extras
.getString("message"), "yoyotrip", false,
PendingIntent.getActivity(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT));
}
}
}
setResultCode(Activity.RESULT_OK);
}
}
You never use your adapter's constructor to create a new instance in GcmBroadcastReceiver. Your adapter will always be null, hence, NullPointerExceptions on that getData() call.
I have made a View Pager in that I want to implement manually slide(OnTOuch) and auto slide(onButton Click)..Both functions are working when use alone.But when i slede from one to another image and start auto Slide,It gives me IllegalStateException..And stops..Please help me to solve it,My code is as below:
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ImagePagerAdapter adapter;
ViewPager viewPager;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
System.out.println(":::::::::::::::current pos::::::::::" + pos);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
Animation anim;
anim = (Animation) getResources().getAnimation(
R.anim.animated_activity_slide_right_in);
viewPager.setAnimation(anim);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
/*
* proImage.setVisibility(View.GONE);
*
* AdapterViewFlipper flipper = (AdapterViewFlipper)
* findViewById(R.id.flipper); flipper.setAutoStart(true);
* flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
* resultArray));
*/
i = 0;
final Handler handler = new Handler();
final Runnable ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
if (i <= adapter.getCount() - 1) {
viewPager.setCurrentItem(i, true);
handler.postDelayed(this, 2000);
i++;
}
}
};
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader.displayImage(resultArray.get(position), imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
Try it and post output or logcat
private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
Log.d("TAG", "mScroller is: " + mScroller + ", "
+ mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is "
+ this + ", " + getClass().getSuperclass().getCanonicalName());
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}
I have this code for compressing pictures , I have two error , I have separated these errors with line in code like this (...........) first is : The left-hand side of an assignment must be a variable .......... and the second is Type mismatch: cannot convert from Object to String ................. how can I fix them ???
package com.example.resizingimages;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
public class GetImageActivity extends Activity
implements MediaScannerConnection.MediaScannerConnectionClient, DialogInterface
{
private static final int CAMERA_REQUEST = 1800;
private static final int GALLERY_KITKAT_INTENT_CALLED = 1500;
private static final int SELECT_PICTURE = 1;
static String filePath;
private TextView Name;
private TextView Size;
MediaScannerConnection conn;
File file;
private String filename;
private int height;
Uri imageUri;
private ImageView img;
private Uri outputFileUri;
Uri outputFileUri1;
String path1;
private String path2;
private Bitmap picture;
private File root;
File sdImageMainDirectory;
private Uri selectedImageUri;
private int width;
private void cameraaa(String paramString, Uri paramUri)
{
while (true)
{
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inSampleSize = 2;
localOptions.inPurgeable = true;
byte[] arrayOfByte = new byte[1024];
localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions.inTempStorage = arrayOfByte;
this.picture = BitmapFactory.decodeStream(localInputStream, null, localOptions);
switch (new ExifInterface(paramString).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str = sizee(paramUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str, 0).show();
System.out.println("Image Path : " + paramString);
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
}
public static String getDataColumn(Context paramContext, Uri paramUri, String paramString, String[] paramArrayOfString)
{
Cursor localCursor = null;
String[] arrayOfString = { "_data" };
try
{
localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, paramString, paramArrayOfString, null);
if ((localCursor != null) && (localCursor.moveToFirst()))
{
String str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
return str;
}
}
finally
{
if (localCursor != null)
localCursor.close();
}
if (localCursor != null)
localCursor.close();
return null;
}
public static String getPathl(Context paramContext, Uri paramUri)
{
int i;
if (Build.VERSION.SDK_INT >= 19)
i = 1;
while ((i != 0) && (DocumentsContract.isDocumentUri(paramContext, paramUri)))
if (isExternalStorageDocument(paramUri))
{
String[] arrayOfString3 = DocumentsContract.getDocumentId(paramUri).split(":");
if (!"primary".equalsIgnoreCase(arrayOfString3[0]))
break label271;
return Environment.getExternalStorageDirectory() + "/" + arrayOfString3[1];
i = 0;
}
else
{
if (isDownloadsDocument(paramUri))
{
String str2 = DocumentsContract.getDocumentId(paramUri);
return getDataColumn(paramContext, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(str2).longValue()), null, null);
}
if (!isMediaDocument(paramUri))
break label271;
String[] arrayOfString1 = DocumentsContract.getDocumentId(paramUri).split(":");
String str1 = arrayOfString1[0];
Uri localUri;
if ("image".equals(str1))
localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
while (true)
{
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = arrayOfString1[1];
return getDataColumn(paramContext, localUri, "_id=?", arrayOfString2);
if ("video".equals(str1))
{
localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else
{
boolean bool = "audio".equals(str1);
localUri = null;
if (bool)
localUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
}
if ("content".equalsIgnoreCase(paramUri.getScheme()))
return getDataColumn(paramContext, paramUri, null, null);
if ("file".equalsIgnoreCase(paramUri.getScheme()))
return paramUri.getPath();
label271: return filePath;
}
public static boolean isDownloadsDocument(Uri paramUri)
{
return "com.android.providers.downloads.documents".equals(paramUri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri paramUri)
{
return "com.android.externalstorage.documents".equals(paramUri.getAuthority());
}
public static boolean isMediaDocument(Uri paramUri)
{
return "com.android.providers.media.documents".equals(paramUri.getAuthority());
}
private void openAddPhoto()
{
String[] arrayOfString = { "Camera", "Gallery" };
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle(getResources().getString(2130968578));
localBuilder.setItems(arrayOfString, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
if (paramAnonymousInt == 0)
{
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", "new-photo-name.jpg");
localContentValues.put("description", "Image capture by camera");
GetImageActivity.this.imageUri = GetImageActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);
Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
localIntent1.putExtra("output", GetImageActivity.this.imageUri);
GetImageActivity.this.startActivityForResult(localIntent1, 1800);
}
if (paramAnonymousInt == 1)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent localIntent2 = new Intent();
localIntent2.setType("image/*");
localIntent2.setAction("android.intent.action.GET_CONTENT");
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent2, "Select Picture"), 1);
}
}
else
return;
Intent localIntent3 = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent3, "Select Picture"), 1500);
}
});
localBuilder.setNeutralButton("cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
private void startScan()
{
if (this.conn != null)
this.conn.disconnect();
this.conn = new MediaScannerConnection(this, this);
this.conn.connect();
}
public void cancel()
{
}
public void dismiss()
{
}
public String getPath(Uri paramUri)
{
Cursor localCursor = managedQuery(paramUri, new String[] { "_data" }, null, null, null);
String str = null;
if (localCursor != null)
{
int i = localCursor.getColumnIndexOrThrow("_data");
localCursor.moveToFirst();
str = localCursor.getString(i);
}
return str;
}
public String name(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
this.filename = filePath.substring(i + 1, paramString.length());
return this.filename;
}
if (paramString.charAt(j) == '/')
i = j;
}
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt2 == -1)
{
if (paramInt1 == 1)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
Toast.makeText(getApplicationContext(), "DATA " + filePath, 0).show();
filePath = getPath(this.selectedImageUri);
InputStream localInputStream2 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
localOptions2.inSampleSize = 2;
localOptions2.inPurgeable = true;
byte[] arrayOfByte2 = new byte[1024];
localOptions2.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions2.inTempStorage = arrayOfByte2;
this.picture = BitmapFactory.decodeStream(localInputStream2, null, localOptions2);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str4 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str4, 0).show();
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException3)
{
Toast.makeText(getApplicationContext(), "Error " + localException3.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
if (paramInt1 == 1500)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
getPathl(getApplicationContext(), this.selectedImageUri);
getContentResolver();
filePath = getPathl(getApplicationContext(), this.selectedImageUri);
InputStream localInputStream1 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
localOptions1.inSampleSize = 2;
localOptions1.inPurgeable = true;
byte[] arrayOfByte1 = new byte[1024];
localOptions1.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions1.inTempStorage = arrayOfByte1;
this.picture = BitmapFactory.decodeStream(localInputStream1, null, localOptions1);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str3 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str3, 0).show();
return;
case 6:
case 3:
}
}
catch (Exception localException2)
{
Toast.makeText(getApplicationContext(), "Error " + localException2.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 90);
continue;
rotateImage(this.picture, 180);
}
if (paramInt1 == 1800)
{
filePath = null;
this.selectedImageUri = this.imageUri;
if (this.selectedImageUri != null)
while (true)
{
String str1;
try
{
str1 = this.selectedImageUri.getPath();
String str2 = getPath(this.selectedImageUri);
if (str2 != null)
{
filePath = str2;
if (filePath == null)
break;
Toast.makeText(getApplicationContext(), " path" + filePath, 1).show();
new Intent(getApplicationContext(), GetImageActivity.class);
cameraaa(filePath, this.selectedImageUri);
return;
}
}
catch (Exception localException1)
{
Toast.makeText(getApplicationContext(), "Internal error", 1).show();
Log.e(localException1.getClass().getName(), localException1.getMessage(), localException1);
return;
}
if (str1 != null)
{
filePath = str1;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path", 1).show();
Log.e("Bitmap", "Unknown path");
}
}
}
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
setContentView(2130903040);
Display localDisplay = getWindowManager().getDefaultDisplay();
this.width = localDisplay.getWidth();
this.height = localDisplay.getHeight();
final Button localButton = (Button)findViewById(2131296257);
final Spinner localSpinner = (Spinner)findViewById(2131296260);
final TextView localTextView = (TextView)findViewById(2131296259);
localButton.setVisibility(4);
localSpinner.setVisibility(4);
localTextView.setVisibility(4);
if (this.height <= 480)
{
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 20 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -20 + (this.height - this.height / 3)));
localTextView.setText("Image Quality");
localTextView.setText("Image Quality");
this.img = ((ImageView)findViewById(2131296258));
this.img.setBackgroundResource(2130837504);
//first error is here
.......................................................................................
***(-160 + this.height);***
(-160 + this.height);
((int)(0.8D * this.width));
AbsoluteLayout.LayoutParams localLayoutParams1 = new AbsoluteLayout.LayoutParams((int)(0.8D * this.width), (int)(0.5D * this.height), (int)(this.width - 0.9D * this.width), (int)(this.height - 0.9D * this.height));
this.img.setLayoutParams(localLayoutParams1);
ImageView localImageView = this.img;
View.OnClickListener local1 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
GetImageActivity.this.img.setImageDrawable(null);
GetImageActivity.this.img.setBackgroundResource(2130837504);
localButton.setVisibility(0);
localSpinner.setVisibility(0);
localTextView.setVisibility(0);
GetImageActivity.this.openAddPhoto();
}
};
localImageView.setOnClickListener(local1);
if (this.height > 480)
break label505;
localButton.setBackgroundResource(2130837507);
(-160 + this.height);
}
for (AbsoluteLayout.LayoutParams localLayoutParams2 = new AbsoluteLayout.LayoutParams(50, 50, -25 + this.width / 2, -51 + this.height); ; localLayoutParams2 = new AbsoluteLayout.LayoutParams(170, 170, -85 + this.width / 2, -170 + this.height))
{
localButton.setLayoutParams(localLayoutParams2);
View.OnClickListener local2 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
}
};
localButton.setOnClickListener(local2);
return;
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 30 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -10 + (this.height - this.height / 3)));
break;
label505: localButton.setBackgroundResource(2130837506);
(-160 + this.height);
}
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(2131230720, paramMenu);
return true;
}
public void onMediaScannerConnected()
{
try
{
this.conn.scanFile(filePath, "image/*");
return;
}
catch (IllegalStateException localIllegalStateException)
{
}
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == 2131296262)
shareagain();
while (true)
{
return true;
if (paramMenuItem.getItemId() == 2131296263)
try
{
startActivity(new Intent(this, readddme.class));
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
}
else if (paramMenuItem.getItemId() == 2131296264)
System.exit(0);
}
}
public void onScanCompleted(String paramString, Uri paramUri)
{
this.conn.disconnect();
}
public void rotateImage(Bitmap paramBitmap, int paramInt)
{
Matrix localMatrix = new Matrix();
localMatrix.setRotate(paramInt);
this.picture = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
}
public void share()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.SUBJECT", "#RABIDO");
localIntent.putExtra("android.intent.extra.TEXT", "#RABIDO");
localIntent.setType("image/*");
localIntent.putExtra("android.intent.extra.STREAM", this.selectedImageUri);
startActivity(Intent.createChooser(localIntent, "Share Image"));
}
public void shareagain()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "Check out 'RABIDO' - https://play.google.com/store/apps/details?id=decrease.image.uploader");
startActivity(Intent.createChooser(localIntent, "Share via"));
}
public String sizee(Uri paramUri)
{
Object localObject;
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
byte[] arrayOfByte = new byte[1024];
int i = 0;
float f;
while (true)
{
if (localInputStream.read(arrayOfByte) == -1)
{
f = i / 1000;
if (f >= 1000.0F)
break;
localObject = " " + i / 1000 + " KB";
break label164;
}
i += arrayOfByte.length;
}
String str = " " + f / 1000.0F + " MB";
localObject = str;
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error 5 " + localException.getMessage(), 0).show();
return "";
}
//second is here
..................................................................
label164: return localObject;
}
}
For the First error can you try something like this:
(this.height = this.height - 160);
The error indicates you are trying to make an assignment operation but you have not put a variable in the left hand side of the equation.
there may also be a short hand way to do this such as:
(this.height =- 160);
for the second error is seems that you have declared "localObject" as an Object.
can you just declare it as a String. seems that you are assigning a string to it and then wanting to return a string. See if that works.
I am developing an application that sends over a webservice information about the last dialed number, call status, and duration of the call.
The application works perfectly fine, but when the device closes the application the android service does restart but the activity does not.
The way I am sure about that is that I have Toasts when the service is started: "Servicio TRUCKA iniciado" and "Servicio TRUCKA creado" tell me that the service has been created and started.
And when the information is sent to the webservice I have toasts saying: "Enviando información..." and "Información enviada."
But when the application is closed (via the android task manager that automatically closes apps) the messages from the service "Servicio TRUCKA iniciado" and "Servicio TRUCKA creado" do appear, but the toasts from the information sent part do not.
I hope someone can help me and tell what am I doing wrong? :)
This is my Activity:
package com.trucka.llamadasdrivers;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import com.trucka.llamadasdrivers.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import android.widget.Toast;
import android.telephony.*;
import android.util.Log;
import java.text.SimpleDateFormat;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class ActividadLlamadasDrivers extends Activity {
TextView txtInformacion = null;
TextView txtDetalles = null;
TextView tv = null;
// Comunicación con el webservice.
private final String NAMESPACE = "http://truckanet.com/MensajeOperador";
// private final String URL =
// "http://192.168.10.94/MensajeOperador/MensajeOperador.asmx";
private final String URL = "http://200.76.187.148/MensajeOperador/MensajeOperador.asmx";
private final String SOAP_ACTION = "http://truckanet.com/MensajeOperador/ActualizarFede";
private final String METHOD_NAME = "ActualizarFede";
private String TAG = "TRUCKA_DRIVERS";
private String resultado;
String phNumber = null;
String callType = null;
String callDate = null;
DateFormat shortFecha = null;
DateFormat shortDF = null;
Date callDayTime = null;
Date fin = null;
String fechaLlamada1 = null;
String fechaLlamada2 = null;
String callDuration = null;
String dir = null;
public String tolo = null;
String imei = null;
String comentario = null;
String fechaRegistro = null;
String insercion = null;
String fechaInicio = null;
String fechaFin = null;
String estadoLlamada = null;
int reinicios = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_llamadas_drivers);
if (!ServicioLlamadas.isRunning()) {
reinicios ++;
Toast.makeText(getApplicationContext(), Integer.toString(reinicios) , Toast.LENGTH_LONG).show();
Intent in = new Intent(ActividadLlamadasDrivers.this,
ServicioLlamadas.class);
ActividadLlamadasDrivers.this.startService(in);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_CALL_STATE);
tv = (TextView) findViewById(R.id.txvEstadoServicio);
txtInformacion = (TextView) findViewById(R.id.textview_call);
txtDetalles = (TextView) findViewById(R.id.textview_call2);
}
}
class TeleListener extends PhoneStateListener {
private boolean telefonoLlamando = false;
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
//getCallDetails();
telefonoLlamando = true;
Toast.makeText(getApplicationContext(),
"Enviando información...", Toast.LENGTH_SHORT).show();
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended,
// need detect flag from CALL_STATE_OFFHOOK
Toast.makeText(getApplicationContext(),
"Información enviada.", Toast.LENGTH_SHORT).show();
if (telefonoLlamando) {
// restart app
getCallDetails();
telefonoLlamando = false;
}
}
}
}
// Obtener la fecha actual del teléfono.
public long getTodayTimestamp() {
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
return c2.getTimeInMillis();
}
// Obtener el detalle de las llamadas con la fecha actual.
#SuppressLint("SimpleDateFormat")
private void getCallDetails() {
String timestamp = String.valueOf(getTodayTimestamp());
StringBuffer sb = new StringBuffer();
#SuppressWarnings("deprecation")
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
CallLog.Calls.DATE + ">= ?", new String[] { timestamp }, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Bitácora de llamadas :");
Integer contador = 0;
// while (managedCursor.moveToNext()) {
// managedCursor.moveToFirst();
managedCursor.moveToLast();
contador = contador + 1;
phNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);
shortFecha = DateFormat.getDateInstance(DateFormat.SHORT);
shortDF = DateFormat.getTimeInstance(DateFormat.SHORT);
callDayTime = new Date(Long.valueOf(callDate));
fechaLlamada1 = shortDF.format(callDayTime);
fechaLlamada2 = shortFecha.format(callDayTime);
callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "Saliente";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "Entrante";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "Perdida";
break;
}
imei = mngr.getDeviceId();
comentario = dir;
fechaRegistro = fechaLlamada2;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String ahorita = df.format(callDayTime);
fechaInicio = ahorita.toString();
// fechaFin =
// df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5));
insercion = "DECLARE #claveDriver INT, #nombreDriver VARCHAR(max), #evento VARCHAR(max), #duracion int, #inicial varchar(max) "
+ "SET #claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"
+ mngr.getDeviceId()
+ "') "
+ "SET #nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"
+ mngr.getDeviceId()
+ "') "
+ "SET #duracion = "
+ managedCursor.getString(duration)
+ "SET #evento = '(LOG) Llamada "
+ dir
+ ". Duración ' + CONVERT(varchar, #duracion, 103) + ' segundos al número: "
+ managedCursor.getString(number)
+ "' "
// + "SET #duracion = " + callDuration
+ " SET #inicial = '"
+ fechaInicio
+ "'"
+ "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) "
+ " VALUES('"
+ fechaInicio
+ "', DATEADD(SECOND,#duracion,#inicial),'"
+ fechaInicio
+ "','"
+ mngr.getDeviceId()
+ "','',#nombreDriver,#claveDriver,current_timestamp,#evento)";
AsyncCallWS tareaEnviarABD = new AsyncCallWS();
tareaEnviarABD.execute();
sb.append("\nNúmero de teléfono:--- " + phNumber
+ " \nTipo de llamada:--- " + dir + " \nFecha de llamada:--- "
+ fechaLlamada2 + " " + fechaLlamada1
+ " \nDuración en segundos:--- " + callDuration
+ " \nDispositivo actual:--" + mngr.getDeviceId());
sb.append("\n----------------------------------");
// }
txtDetalles.setText(sb);
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
InsertarLlamada(insercion);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
txtInformacion.setText("Información enviada");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
txtInformacion.setText("Enviando información...");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
public void InsertarLlamada(String insercion) {
// Creamos la solicitud
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Propiedades que contienen los valores
PropertyInfo propiedades = new PropertyInfo();
propiedades.setName("insercion");
propiedades.setValue(insercion);
propiedades.setType(String.class);
// Agregamos las propiedades
request.addProperty(propiedades);
// Creamos el envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
// ponemos la salida SOAP
envelope.setOutputSoapObject(request);
// Creamos la llamada HTTP
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
// Invocamos el servicio
androidHttpTransport.call(SOAP_ACTION, envelope);
// Obtenemos la respuesta
Object response = envelope.getResponse();
// Asignamos el resultado de la consulta
resultado = response.toString();
} catch (Exception e) {
resultado = e.getMessage();
}
}
}
}
BootReceiver class:
package com.trucka.llamadasdrivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, ActividadLlamadasDrivers.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
Llamadas service:
package com.trucka.llamadasdrivers;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.widget.Toast;
public class ServicioLlamadas extends Service {
private static ServicioLlamadas instance = null;
public static boolean isRunning() {
return instance != null;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA creado",
Toast.LENGTH_SHORT).show();
instance = this;
}
#Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA destruído",
Toast.LENGTH_SHORT).show();
instance = null;
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA iniciado",
Toast.LENGTH_SHORT).show();
lanzarNotificacion();
}
#SuppressWarnings("deprecation")
void lanzarNotificacion() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notManager = (NotificationManager) getSystemService(ns);
// Configuramos la notificacion
Notification notif = new Notification(
android.R.drawable.ic_menu_agenda, "Servicio TRUCKA",
System.currentTimeMillis());
// Configuramos el Intent
Context contexto = ServicioLlamadas.this;
CharSequence titulo = "Notificación Servicio TRUCKA";
CharSequence descripcion = "Registro habilitado.";
// Intent que se abrira al clickear la notificacion
PendingIntent contIntent = PendingIntent.getActivity(contexto, 0, null,
0);
notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_VIBRATE;
notManager.notify(1, notif);
}
}
And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.trucka.llamadasdrivers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.trucka.llamadasdrivers.ActividadLlamadasDrivers"
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="com.trucka.llamadasdrivers.ServicioLlamadas"
android:enabled="true"
android:icon="#drawable/ic_launcher" >
</service>
<receiver android:name=".BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Human stupidity has no limits.
My actines where not in the service