Webview in Flutter - How to handle Webview in Flutter from u/rrtutors
Showing posts with label Home. Show all posts
Showing posts with label Home. Show all posts
Thursday, 17 September 2020
Monday, 26 February 2018
Download files in background service
Service classclass DownloadService extends IntentService {RetrofitConnection retrofitInterface;public DownloadService() {super("Download Service");}private NotificationCompat.Builder notificationBuilder;private NotificationManager notificationManager;private int totalFileSize;private String image_url;int type;String filename;@Override protected void onHandleIntent(Intent intent) {if (intent.getExtras() != null && intent != null) {image_url = intent.getStringExtra("img");type = intent.getIntExtra("type", 0);filename = intent.getStringExtra("filename");Log.e("TYPE", "" + type);}notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);notificationBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.downd).setContentTitle("Download").setContentText("Downloading image").setAutoCancel(true);notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;notificationManager.notify(0, notificationBuilder.build());if (NetworkChecking.isConnected(getApplicationContext())) {initDownload(image_url);} else {Utils.toastMessage(getApplicationContext(),Utils.network_message);}}private void initDownload(String url) {downloadFile(request.execute().body());} catch (IOException e) {e.printStackTrace();Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_SHORT).show();}}private void downloadFile(ResponseBody body) throws IOException {int count;byte data[] = new byte[1024 * 4];long fileSize = body.contentLength();InputStream bis = new BufferedInputStream(body.byteStream(),1024 * 8);Log.e("outputFile", "" + outputFile);OutputStream output = new FileOutputStream(outputFile);long total = 0;long startTime = System.currentTimeMillis();int timeCount = 1;while ((count = bis.read(data)) != -1) {total += count;totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));double current = Math.round(total / (Math.pow(1024, 2)));int progress = (int) ((total * 100) / fileSize);long currentTime = System.currentTimeMillis() - startTime;Download download = new Download();download.setTotalFileSize(totalFileSize);if (currentTime > 1000 * timeCount) {download.setCurrentFileSize((int) current);download.setProgress(progress);sendNotification(download,outputFile.getPath());timeCount++; }output.write(data, 0, count);}onDownloadComplete(outputFile.getPath());output.flush(); output.close();private void sendNotification(Download download,String filePath) {bis.close(); }File file = new File(filePath);MimeTypeMap map = MimeTypeMap.getSingleton();String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());String type = map.getMimeTypeFromExtension(ext);if (type == null)type = "*/*";Intent intent = new Intent(Intent.ACTION_VIEW);Uri data = Uri.fromFile(file);intent.setDataAndType(data, type);sendIntent(download);notificationBuilder.setProgress(100, download.getProgress(),false);notificationBuilder.setContentText("Downloading file " +download.getCurrentFileSize() + "/" + totalFileSize + " MB");notificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, intent,PendingIntent.FLAG_CANCEL_CURRENT));notificationManager.notify(0, notificationBuilder.build());}private void sendIntent(Download download) {Intent intent = new Intent(ShowImageActivity.MESSAGE_PROGRESS);intent.putExtra("download", download);LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);}private void onDownloadComplete(String filePath) {Download download = new Download();download.setProgress(100);sendIntent(download);File file = new File(filePath);MimeTypeMap map = MimeTypeMap.getSingleton();String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());String type = map.getMimeTypeFromExtension(ext);if (type == null)type = "*/*";Intent intent = new Intent(Intent.ACTION_VIEW);Uri data = Uri.fromFile(file);intent.setDataAndType(data, type);notificationManager.cancel(0);notificationBuilder.setProgress(0, 0, false);notificationBuilder.setContentText("File Downloaded");notificationBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, intent,PendingIntent.FLAG_CANCEL_CURRENT));notificationManager.notify(0, notificationBuilder.build());}@Override public void onTaskRemoved(Intent rootIntent) {notificationManager.cancel(0);}public File getOutputMediaFile(int type) {String folder_name = "TYC";File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/" + folder_name, "IMAGES");if (!mediaStorageDir.exists()) {mediaStorageDir.mkdirs();}File f1 = new File(Environment.getExternalStorageDirectory()+ "/" + folder_name, "DOCUMENTS");if (!f1.exists()) {f1.mkdirs();}Locale.getDefault()).format(new Date());File mediaFile;mediaFile = new File(mediaStorageDir.getPath() +File.separator + "img_" + timeStamp + ".jpg");} else if (type == 2) {mediaFile = new File(f1.getPath() + File.separator+ "PDF_" + timeStamp + ".pdf");} else if (type == 3) {mediaFile = new File(f1.getPath() + File.separator+ filename);}else {return null;}return mediaFile;} }Call service from Button clickIntent intent = new Intent(getActivity(), DownloadService.class);intent.putExtra("img", "pass your file path");intent.putExtra("type", 3);intent.putExtra("filename", "Pass here your file name");startService(intent);
Saturday, 26 August 2017
Images/Icon sizes for different devices
Developer will think about what size of icons/images have to use for application that will support for different devices.
Please follow below ratio for images/icons
Please follow below ratio for images/icons
Role / Screen | LDPI | MDPI | HDPI | XHDPI |
----------------------------------------------------
Icon | 36x36 | 48x48 | 72x72 | 96x96 |
----------------------------------------------------
Thumbnail | 72x72 | 96x96 | 144x144| 192x192 |
----------------------------------------------------
Full | 240x320|320x480 | 480x800| 720x1280|
Wednesday, 21 December 2016
Retrofit in Android
Retrofit is a type-safe REST client for Android developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp
Integrate Retrofit in Android follow Below steps:
1) Add dependencies in build.gradle file
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
2) Create Interface which will have all the api callspublic interface DataCall{ //Get Method Call @GET("Pass your api path) //ex: "register.php" Call<String>getDataGet(@Query("name") String name);//Post Method Call@FormUrlEncoded @POST("index.php") Call<String>getDataPost(@Field("name")String name);//Post Method Call with Query annotation@POST("index.php") Call<String>getDataPostQuery(@Query("name")String name); //Post Method Call with HashMap request
@POST("index.php")
Call<String>getDataPostQueryMap(@QueryMap HashMap<String,String> map);
//Post Method Call with Json request
@POST("index.php")
Call<String>getDataPostQueryJson(@Body RequestBody name);
}
3) Create Retrofit object and call api methods.
Retrofit retrofit = new Retrofit.Builder().baseUrl("pass here your base url,shoul end with /") .addConverterFactory(ScalarsConverterFactory.create()).build();//ScalarsConverterFactory.create() is for String response handling//GsonConverterFactory.create() is used for automatically will parse the//response with proper bean classesDataCall datacall = retrofit.create(DataCall.class);
//Get Method call
Call<String> call = datacall.getDataGet("GET name");call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,Response<String> response) { System.out.println("Response data :"+response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { System.out.println("Response data :"+t.getMessage()); } });//Post Method callcall = datacall.getDataPost("POST name"); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,Response<String> response) { System.out.println("Response data :"+response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { System.out.println("Response data :"+t.getMessage()); } });//Post Method callcall = datacall.getDataPostQuery("POST Query"); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,Response<String> response) { System.out.println("Response data :"+response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { System.out.println("Response data :"+t.getMessage()); } });//Post Method call with Hash map requestHashMap<String,String>map=new HashMap(); JSONObject ob2=null; // JSONObject map=new JSONObject(); try { map.put("name1", "Map name"); map.put("password1", "Map password"); ob2=new JSONObject(map); }catch (Exception e) { e.printStackTrace();; } RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),ob2.toString()); call = datacall.getDataPostQueryJson(body); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call,Response<String> response) { System.out.println("Response data :"+response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { System.out.println("Response data :"+t.getMessage()); } });
//Post Method call with JSon Request
JSONObject map=new JSONObject();
try {
map.put("name1", "Map name");
map.put("password1", "Map password");
}catch (Exception e)
{
e.printStackTrace();;
}
RequestBody body = RequestBody.
create(okhttp3.MediaType.parse("application/json; charset=utf-8"),map.toString());
call = datacall.getDataPostQueryJson(body);
call.enqueue(new Callback<String>() {
@Override public void onResponse(Call<String> call,
Response<String> response) {
System.out.println("Response data :"+response.body());
}
@Override public void onFailure(Call<String> call, Throwable t) {
System.out.println("Response data :"+t.getMessage());
}
});
Wednesday, 2 November 2016
Android Notifications
Notification creation in android has updated with few methods are deprecated in Marsh Mallows Version
I have created notification in differert formats
check below Fragment class and xml files
/**
* A fragment that enables display of notifications.
*/
public class ActiveNotificationFragment extends Fragment {
private static final String TAG = "ActiveNotificationFragment";
private NotificationManager mNotificationManager;
private TextView mNumberOfNotifications;
// Every notification needs a unique ID otherwise the previous one would be overwritten.
private int mNotificationId = 0;
private PendingIntent mDeletePendingIntent;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_notification_builder, container, false);
}
@Override
public void onResume() {
super.onResume();
updateNumberOfNotifications();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mNotificationManager = (NotificationManager) getActivity().getSystemService(
Context.NOTIFICATION_SERVICE);
mNumberOfNotifications = (TextView) view.findViewById(R.id.number_of_notifications);
// Supply actions to the button that is displayed on screen.
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_notification:
addNotificationAndReadNumber();
break;
case R.id.add_notification_big:
addBigText();
break;
case R.id.add_notification_big_image:
addBigImage();
break;
case R.id.add_notification_heads:
addHeadsUpNotification();
break;
case R.id.add_notification_action:
customNotification();
break;
}
}
};
view.findViewById(R.id.add_notification).setOnClickListener(onClickListener);
view.findViewById(R.id.add_notification_big).setOnClickListener(onClickListener);
view.findViewById(R.id.add_notification_big_image).setOnClickListener(onClickListener);
view.findViewById(R.id.add_notification_heads).setOnClickListener(onClickListener);
view.findViewById(R.id.add_notification_action).setOnClickListener(onClickListener);
// Create a PendingIntent to be fired upon deletion of a Notification.
Intent deleteIntent = new Intent("YOUR ACTIVITY/BORADCASTRECEIVER";
mDeletePendingIntent = PendingIntent.getBroadcast(getActivity(),
2 /* requestCode */, deleteIntent, 0);
}
/**
* Add a new {@link Notification} with sample data and send it to the system.
* Then read the current number of displayed notifications for this application.
*/
private void addNotificationAndReadNumber() {
// [BEGIN create_notification]
// Create a Notification and notify the system.
final Notification.Builder builder = new Notification.Builder(getActivity())
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.sample_notification_content))
.setAutoCancel(true)
.setDeleteIntent(mDeletePendingIntent);
builder.setContentIntent(getPendingIntent());
final Notification notification = builder.build();
mNotificationManager.notify(++mNotificationId, notification);
// [END create_notification]
Log.i(TAG, "Add a notification");
updateNumberOfNotifications();
}
private void addBigText()
{
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Event tracker")
.setContentText("Events received")/*.
setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVibrate(new long[] {1, 1, 1})*/;
/* Intent push = new Intent();
push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
push.setClass(getActivity(), MainActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(getActivity(), 0,
push, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder
.setContentText("A Heads-Up notification for Lollipop and above")
.setFullScreenIntent(fullScreenPendingIntent, true);
*/
// notificationManager.notify(HEADS_UP_NOTIFICATION_ID, notificationBuilder.build());
mBuilder .setAutoCancel(true);
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
// Moves events into the expanded layout
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]+" : "+i);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inboxStyle);
mBuilder.setContentIntent(getPendingIntent());
Notification notification=mBuilder.build();
// mBuilder.setAutoCancel(true);
mNotificationManager.notify(++mNotificationId, notification);
updateNumberOfNotifications();
}
private void addBigImage()
{
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Event tracker")
.setContentText("Events received")
;
NotificationCompat.BigPictureStyle inboxStyle =
new NotificationCompat.BigPictureStyle();
String[] events = new String[6];
inboxStyle.setBigContentTitle("Event tracker details:");
inboxStyle.bigPicture(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
// Moves events into the expanded layout
mBuilder.setAutoCancel(true);
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inboxStyle);
mBuilder.setContentIntent(getPendingIntent());
Notification notification=mBuilder.build();
mNotificationManager.notify(++mNotificationId, notification);
updateNumberOfNotifications();
}
private void addHeadsUpNotification()
{
Notification.Builder builder=new Notification.Builder(getActivity());
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setPriority(Notification.PRIORITY_HIGH);
builder.setVibrate(new long[]{100,200,100});
builder.setContentTitle("HeadsUpNotification");
builder.setContentIntent(getPendingIntent());
builder.setAutoCancel(true);
mNotificationManager.notify(++mNotificationId,builder.build());
}
/**
* Request the current number of notifications from the {@link NotificationManager} and
* display them to the user.
*/
protected void updateNumberOfNotifications() {
// [BEGIN get_active_notifications]
// Query the currently displayed notifications.
if(Build.VERSION.SDK_INT<Build.VERSION_CODES.M)
return;
final StatusBarNotification[] activeNotifications = mNotificationManager
.getActiveNotifications();
// [END get_active_notifications]
final int numberOfNotifications = activeNotifications.length;
mNumberOfNotifications.setText(getString(R.string.active_notifications,
numberOfNotifications));
Log.i(TAG, getString(R.string.active_notifications, numberOfNotifications));
}
private PendingIntent getPendingIntent()
{
Intent intent=new Intent(getActivity(),SeconActivity.class);
PendingIntent pending=PendingIntent.getActivity(getActivity(),0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
return pending;
}
private void customNotification()
{
RemoteViews remoteview=new RemoteViews(getActivity().getPackageName(),R.layout.remoteview);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity())
.setContent(remoteview).setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setAutoCancel(true);
Notification notification=notificationBuilder.build();
remoteview.setOnClickPendingIntent(R.id.img,PendingIntent.getActivity(getActivity(),0,new Intent(getActivity(),SeconActivity.class),PendingIntent.FLAG_CANCEL_CURRENT));
notification.bigContentView = remoteview;
notification.flags|=Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(++mNotificationId,notification);
}
}
XML File
------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/add_notification"
android:text="@string/add_a_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add_notification_big"
android:text="BigText Notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add_notification_big_image"
android:text="BigImage Notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add_notification_heads"
android:text="HeadsUp notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add_notification_action"
android:text="Action notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
style="@android:style/TextAppearance.Material.Large"
android:id="@+id/number_of_notifications"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
remoteview layout
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/img"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#d94cd9"
android:text="Title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#e10a23"
android:text="Description"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#c4612c"
android:text="Title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#a7ab42"
android:text="Description"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#701770"
android:text="Title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#5a51bc"
android:text="Description"/>
</LinearLayout>
<ImageView android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:layout_alignParentRight="true"/>
</RelativeLayout>
Migrate Android Eclipse project into Android studio
- Open Studio file->import new project
- Check all checkBoxes which will update the project with latest library’s submit finish button. If your project as external library projects It will add the External library projects as module.
- if library project are not added as module
- Go to library project and create build.gradle file
- Go to studio and import module, select modified file
- Now update the module gradle file.
Import Existing Eclipse Remote Application into Android Studio
- Checkout existing project into local machine. => svn co “remote path”
- Delete ANT build related files (like .classpath,.project files)
- Start studio and import project from local directory (Check VSC enabled or not, if not enable it).
- Project is imported as Android studio project.
- Now add manually necessary library project as module which it has previously.
- Run the app.
- Commit changes through terminal =>svn commit
- Enable VCS for current project =>VCS =>Enable VCS
- Commit Through IDE VCS=>Subversion=>Commit file/Commit Directory
Few SVN Commands
- svn checkout/co “repository path”
- svn add “file/folder”
- svn delete “file/folder”
- svn status
- svn update/up
- svn commit/ci
- svn diff
In Ubuntu install SVN by using this command in terminal “sudo apt-get install subversion”
In Windows use Tortoise Subversion
Add new Project to SVN
In Studio- Enable VCS
- Select Share Project To Subversion in VCS dialog
- Add the repository in Dialog box
- Commit
- svn mkdir "Parent repositoryPath"+"/new project folder"
- Go to parent folder of your project cd /
- svn co "path of repository"(includes project folder which created)
- svn add "project folder"(until commit your project it won't show in repository) => by using svn st command we can check the files what we have to add.
- svn commit
Friday, 27 December 2013
Google Cloud Messaging(GCM) in Android
Follow the Below Steps
-------------------------
Create a Google API Project
------------------------------
-----------------------------------
goes Services and turn the Google Cloud Messaging for Android toggle to ON
Generate API Key
--------------------
goes to API Access
click new Android key, then window will be opened, enter your SHA1 key along with your project package name then click on create button
you will get an api key, copy this key and use it in later
MainActivity.java
-------------------
public class MainActivityextends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isNetworkAvailable()) {
if(GCMMessaging.getRegistrationId(MainActivity.this).equals("n/a"))
{
GCMMessaging.requestRegistration(SplashSceen.this);
}
}
else{
Toast.makeText(getApplicationContext(),"No network connection ",3000).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
}
MyIntentService
-------------------
public class MyIntentService extends IntentService {
@SuppressWarnings("unused")
private String senderId = Constants.senderId;
private static int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock sWakeLock;
static String TAG = "MyIntentService";
public MyIntentService() {
super("MyService");
// TODO Auto-generated constructor stub
}
public MyIntentService(String senderId) {
// senderId is used as base name for threads, etc.
super(senderId);
this.senderId = senderId;
}
private static final Object LOCK = MyIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized (LOCK) {
Log.v(TAG, "runIntentInService1");
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, MyIntentService.class.getName());
context.startService(intent);
Log.v(TAG, "runIntentInService finish");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
try {
String action = intent.getAction();
Log.v(TAG, "onHandleIntent" + action);
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
Log.v(TAG, "REGISTRATION");
handleRegistration(MyIntentService.this, intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(MyIntentService.this, intent);
Log.v(TAG, "RECEIVE MESSAGE");
} else if (action.equals("com.google.android.c2dm.intent.RETRY")) {
GCMMessaging.requestRegistration(MyIntentService.this);
Log.v(TAG, "RETRY");
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
private void handleRegistration(Context context, Intent intent) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
// Registration failed, should try again later.
Log.d("GCM", "registration failed");
String error = intent.getStringExtra("error");
if (error == "SERVICE_NOT_AVAILABLE") {
Log.d("GCM", "SERVICE_NOT_AVAILABLE");
} else if (error == "ACCOUNT_MISSING") {
Log.d("GCM", "ACCOUNT_MISSING");
} else if (error == "AUTHENTICATION_FAILED") {
Log.d("GCM", "AUTHENTICATION_FAILED");
} else if (error == "TOO_MANY_REGISTRATIONS") {
Log.d("GCM", "TOO_MANY_REGISTRATIONS");
} else if (error == "INVALID_SENDER") {
Log.d("GCM", "INVALID_SENDER");
} else if (error == "PHONE_REGISTRATION_ERROR") {
Log.d("GCM", "PHONE_REGISTRATION_ERROR");
} else {
Log.d("GCM", "REGISTRATION_ERROR");
}
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, "n/a");
editor.putString(Constants.ERROR_DESC, error);
editor.commit();
} else if (intent.getStringExtra("unregistered") != null) {
// unregistration done, new messages from the authorized sender will
// be rejected
Log.d("GCM", "unregistered");
unregisterWithServer(context);
} else if (registration != null) {
Log.d("GCM registration ! null", registration);
saveRegistrationId(context, registration);
sendRegistrationIdToServer(registration);
}
}
private void handleMessage(Context context, Intent intent) {
Log.v("############GCM############", "Received message");
Intent intent1;
// String message = intent.getStringExtra("data");
// String s=message.toString();
String data = intent.getExtras().getString("message");
String type = intent.getStringExtra("type");
Intent intent =new Intent();
Log.v("############GCM##############", "dmControl: message = " + data);
// TODO Send this to my application server to get the real data
// Lets make something visible to show that we received the message
createNotification(context, data, type,intent);
}
private void saveRegistrationId(Context context, String registrationId) {
Log.v("GCM saveregistration id", registrationId);
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, registrationId);
editor.putString(Constants.ERROR_DESC, "null");
editor.commit();
}
// public void sendRegistrationIdToServer(String deviceId,String
// registrationId)
public void sendRegistrationIdToServer(String registrationId) {
Log.v("GCM", "Sending registration ID to my application server");
// write code for your webservice
}
@SuppressWarnings("deprecation")
public void createNotification(Context context, String data, String type,Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Title" + data, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
PendingIntent pendingIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, "title", "" + data,
pendingIntent);
notificationManager.notify(NOTIFICATION_ID++, notification);
}
private void unregisterWithServer(Context context) {
// TODO Auto-generated method stub
}
}
GCMMessaging
------------------
public class GCMMessaging {
private static final long DEFAULT_BACKOFF = 30000;
public static final String BACKOFF = "backoff";
static final String PREFERENCE = "exp_back_off";
static String tag = "Messaging class";
static long getBackoff(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}
static void setBackoff(Context context, long backoff) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putLong(BACKOFF, backoff);
editor.commit();
}
public static void requestRegistration(Context context) {
// TODO Auto-generated method stub
Log.v(tag, "requestRegistrationId method called sender id");
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// Sender id - project ID generated when signing up
intent.putExtra("sender", Constants.senderId);
context.startService(intent);
}
public static String getRegistrationId(Context context) {
SharedPreferences prefs = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
String registraionId = prefs.getString(Constants.REGISTRATION_KEY, "n/a");
return registraionId;
}
public static void removeRegistrationId(Context context) {
SharedPreferences settings = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = settings.edit();
edit.putString(Constants.REGISTRATION_KEY, "n/a"); // registration id
edit.commit(); //apply
}
}
GCMReceiver
-----------------
public class GCMReceiver extends BroadcastReceiver
{
Context context;
String TAG = "GCM receiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Registration Receiver called");
Log.v("#############"+TAG+"###############", "Receiver: "+intent.getAction());
this.context = context;
MyIntentService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
Constants.java
------------------
public class Constants
{
public static String senderId="enter your project id";
public static String KEY = "enter your key";
public static String REGISTRATION_KEY = "n/a";
public static String ERROR_DESC = "errorDesc";*/
}
write permissions in manifest file
-----------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="packagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="packagename.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
copy services
----------------
<receiver
android:name="packageName.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
- <!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="packageName" />
</intent-filter>
- <!-- Receive the registration id -->
- <intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packageName" />
</intent-filter>
</receiver>
<service android:name="packageName.MyIntentService" />
Server side Code
-------------------
write code for sending message,device token and api key to GCMServer from your server
-------------------------
Create a Google API Project
------------------------------
- Open the Google Cloud Console.
- If you haven't created an API project yet, click Create Project.
- Add project name and click Create.
- Once the project has been created, a page appears that displays your project ID and project number.
- Copy your project number, this is your GCM sendeIdnumber
-----------------------------------
goes Services and turn the Google Cloud Messaging for Android toggle to ON
Generate API Key
--------------------
goes to API Access
click new Android key, then window will be opened, enter your SHA1 key along with your project package name then click on create button
you will get an api key, copy this key and use it in later
MainActivity.java
-------------------
public class MainActivityextends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isNetworkAvailable()) {
if(GCMMessaging.getRegistrationId(MainActivity.this).equals("n/a"))
{
GCMMessaging.requestRegistration(SplashSceen.this);
}
}
else{
Toast.makeText(getApplicationContext(),"No network connection ",3000).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
}
MyIntentService
-------------------
public class MyIntentService extends IntentService {
@SuppressWarnings("unused")
private String senderId = Constants.senderId;
private static int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock sWakeLock;
static String TAG = "MyIntentService";
public MyIntentService() {
super("MyService");
// TODO Auto-generated constructor stub
}
public MyIntentService(String senderId) {
// senderId is used as base name for threads, etc.
super(senderId);
this.senderId = senderId;
}
private static final Object LOCK = MyIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized (LOCK) {
Log.v(TAG, "runIntentInService1");
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, MyIntentService.class.getName());
context.startService(intent);
Log.v(TAG, "runIntentInService finish");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
try {
String action = intent.getAction();
Log.v(TAG, "onHandleIntent" + action);
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
Log.v(TAG, "REGISTRATION");
handleRegistration(MyIntentService.this, intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(MyIntentService.this, intent);
Log.v(TAG, "RECEIVE MESSAGE");
} else if (action.equals("com.google.android.c2dm.intent.RETRY")) {
GCMMessaging.requestRegistration(MyIntentService.this);
Log.v(TAG, "RETRY");
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
private void handleRegistration(Context context, Intent intent) {
String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) {
// Registration failed, should try again later.
Log.d("GCM", "registration failed");
String error = intent.getStringExtra("error");
if (error == "SERVICE_NOT_AVAILABLE") {
Log.d("GCM", "SERVICE_NOT_AVAILABLE");
} else if (error == "ACCOUNT_MISSING") {
Log.d("GCM", "ACCOUNT_MISSING");
} else if (error == "AUTHENTICATION_FAILED") {
Log.d("GCM", "AUTHENTICATION_FAILED");
} else if (error == "TOO_MANY_REGISTRATIONS") {
Log.d("GCM", "TOO_MANY_REGISTRATIONS");
} else if (error == "INVALID_SENDER") {
Log.d("GCM", "INVALID_SENDER");
} else if (error == "PHONE_REGISTRATION_ERROR") {
Log.d("GCM", "PHONE_REGISTRATION_ERROR");
} else {
Log.d("GCM", "REGISTRATION_ERROR");
}
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, "n/a");
editor.putString(Constants.ERROR_DESC, error);
editor.commit();
} else if (intent.getStringExtra("unregistered") != null) {
// unregistration done, new messages from the authorized sender will
// be rejected
Log.d("GCM", "unregistered");
unregisterWithServer(context);
} else if (registration != null) {
Log.d("GCM registration ! null", registration);
saveRegistrationId(context, registration);
sendRegistrationIdToServer(registration);
}
}
private void handleMessage(Context context, Intent intent) {
Log.v("############GCM############", "Received message");
Intent intent1;
// String message = intent.getStringExtra("data");
// String s=message.toString();
String data = intent.getExtras().getString("message");
String type = intent.getStringExtra("type");
Intent intent =new Intent();
Log.v("############GCM##############", "dmControl: message = " + data);
// TODO Send this to my application server to get the real data
// Lets make something visible to show that we received the message
createNotification(context, data, type,intent);
}
private void saveRegistrationId(Context context, String registrationId) {
Log.v("GCM saveregistration id", registrationId);
Editor editor = context.getSharedPreferences(Constants.KEY,
Context.MODE_PRIVATE).edit();
editor.putString(Constants.REGISTRATION_KEY, registrationId);
editor.putString(Constants.ERROR_DESC, "null");
editor.commit();
}
// public void sendRegistrationIdToServer(String deviceId,String
// registrationId)
public void sendRegistrationIdToServer(String registrationId) {
Log.v("GCM", "Sending registration ID to my application server");
// write code for your webservice
}
@SuppressWarnings("deprecation")
public void createNotification(Context context, String data, String type,Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Title" + data, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
PendingIntent pendingIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, "title", "" + data,
pendingIntent);
notificationManager.notify(NOTIFICATION_ID++, notification);
}
private void unregisterWithServer(Context context) {
// TODO Auto-generated method stub
}
}
GCMMessaging
------------------
public class GCMMessaging {
private static final long DEFAULT_BACKOFF = 30000;
public static final String BACKOFF = "backoff";
static final String PREFERENCE = "exp_back_off";
static String tag = "Messaging class";
static long getBackoff(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
return prefs.getLong(BACKOFF, DEFAULT_BACKOFF);
}
static void setBackoff(Context context, long backoff) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCE,
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putLong(BACKOFF, backoff);
editor.commit();
}
public static void requestRegistration(Context context) {
// TODO Auto-generated method stub
Log.v(tag, "requestRegistrationId method called sender id");
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",
PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// Sender id - project ID generated when signing up
intent.putExtra("sender", Constants.senderId);
context.startService(intent);
}
public static String getRegistrationId(Context context) {
SharedPreferences prefs = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
String registraionId = prefs.getString(Constants.REGISTRATION_KEY, "n/a");
return registraionId;
}
public static void removeRegistrationId(Context context) {
SharedPreferences settings = context.getSharedPreferences(Constants.KEY,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = settings.edit();
edit.putString(Constants.REGISTRATION_KEY, "n/a"); // registration id
edit.commit(); //apply
}
}
GCMReceiver
-----------------
public class GCMReceiver extends BroadcastReceiver
{
Context context;
String TAG = "GCM receiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Registration Receiver called");
Log.v("#############"+TAG+"###############", "Receiver: "+intent.getAction());
this.context = context;
MyIntentService.runIntentInService(context, intent);
setResult(Activity.RESULT_OK, null, null);
}
}
Constants.java
------------------
public class Constants
{
public static String senderId="enter your project id";
public static String KEY = "enter your key";
public static String REGISTRATION_KEY = "n/a";
public static String ERROR_DESC = "errorDesc";*/
}
write permissions in manifest file
-----------------------------------
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="packagename.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="packagename.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
copy services
----------------
<receiver
android:name="packageName.GCMReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
- <!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="packageName" />
</intent-filter>
- <!-- Receive the registration id -->
- <intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="packageName" />
</intent-filter>
</receiver>
<service android:name="packageName.MyIntentService" />
Server side Code
-------------------
write code for sending message,device token and api key to GCMServer from your server
Subscribe to:
Posts (Atom)