How to initialize the parse.com code in Android - android

I am trying to use the Parse.com sdk and I can't get my Parse codes to initialize. I don't know where to put it and I need help because I can't tell if I need to put it in my main or if I need to put it in somewhere else.
This is a few blocks of code I have put in different classes
I created this with the sample
package com.example.musicdroid;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseUser;
import android.app.Application;
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Add your initialization code here
Parse.initialize(this, "XXX", "XXX");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseACL.setDefaultACL(defaultACL, true);
}
}
This is where I had it originally
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choices = { "Rock", "Metal", "Rap", "My Favorites" };
setListAdapter(new ArrayAdapter<String>(this, R.layout.main,
R.id.music, choices));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("spotify:user:warnermusicus:playlist:3DRD3GUpQSjK2rryIRVOPS")));
} catch (ActivityNotFoundException e) {
final Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.spotify.mobile.android.ui"));
startActivity(intent);
}
break;
case 1:
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("spotify:user:warnermusicus:playlist:6iIDHF5tBqzS6uZjMEzBdQ")));
} catch (ActivityNotFoundException e) {
final Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.spotify.mobile.android.ui"));
startActivity(intent);
}
break;
case 2:
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("spotify:user:digsterdeutschland:playlist:5pvJLjAhcKCHXGOb7pEbBZ")));
} catch (ActivityNotFoundException e) {
final Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.spotify.mobile.android.ui"));
startActivity(intent);
}
break;
case 3:
try {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("spotify:user:digsterdeutschland:playlist:1hYWCuFv5Eav9yIZXHwnpd")));
} catch (ActivityNotFoundException e) {
final Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.spotify.mobile.android.ui"));
startActivity(intent);
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Another place I had it. This is the Main Menu
package com.example.musicdroid;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainMenu extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choices = { "Main", "Bios", "Artist Search", "How To Use" };
setListAdapter(new ArrayAdapter<String>(this, R.layout.menu, R.id.Menu,
choices));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(MainMenu.this, Main.class));
break;
case 1:
startActivity(new Intent(MainMenu.this, Bios.class));
break;
case 2:
startActivity(new Intent(MainMenu.this, Search.class));
break;
case 3:
startActivity(new Intent(MainMenu.this, How.class));
break;
}
}
}
Manifest Code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.musicdroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="com.example.musicdroid.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.musicdroid.permission.C2D_MESSAGE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/fiery_music_symbol"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo" >
<activity
android:name="com.example.musicdroid.Main"
android:label="#string/app_name" >
</activity>
<activity android:name=".MainMenu" >
</activity>
<activity android:name=".Bios" >
</activity>
<activity android:name=".Search" >
</activity>
<activity android:name=".How" >
</activity>
<activity android:name=".LoginSignupActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Welcome" >
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.musicdroid" />
</intent-filter>
</receiver>
</application>
</manifest>

Add Your class extending Application inside Manifest File
<application android:name="your packagename.ParseApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
I hope this helps..

Just put it to your MainActivity.java to onCreate with all the statements, which you have in ParseApplication's class onCreate. Then you can remove this class (ParseApplication.java)
It should work properly.
Hope it helps

You should always place the initialize call in the ACTIVITY's onCreate method, just after the setContentView call. Like this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name_here);
Parse.initialize(this, "ApplicationKey", "ClientKey);
// Rest of your code follows...
}
Once you have that line, you can then do any Parse transactions.

Say you can't have custom app class (Eg: Android Library)
You can use the following procedure
Call initialize like this:
if (ParseCheck.isParseInitialized())
Parse.initialize(context, PARSE.AB4FUN_APP.APPLICATION_ID, PARSE.AB4FUN_APP.CLIENT_KEY);
Create a utility class like below (note the package)
package com.parse;
public class ParseCheck {
public static boolean isParseInitialized(){
return Parse.isInitialized();
}
}

import android.app.Application;
import com.parse.Parse;
public class MyApp extends Application {
#Override public void onCreate() {
super.onCreate();
Parse.initialize(this, ApplicationID, ClientKey);
}
}
Then, add the following to your <application> in AndroidManifest.xml:
name=".MyApp"

Related

Calling another class from MainActivity in OnCreate()

I have two main classes in my application for activity launch as.
MainActivity.Java
package com.connect;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private PolicyManager policyManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policyManager = new PolicyManager(this);
System.out.println("Hello");
if (!policyManager.isAdminActive()) {
Intent activateDeviceAdmin = new Intent(
DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
activateDeviceAdmin.putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN,
policyManager.getAdminComponent());
activateDeviceAdmin
.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"After activating admin, you will be able to block application uninstallation.");
startActivityForResult(activateDeviceAdmin,
PolicyManager.DPM_ACTIVATION_REQUEST_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == Activity.RESULT_OK
&& requestCode == PolicyManager.DPM_ACTIVATION_REQUEST_CODE) {
// handle code for successfull enable of admin
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Droidian.java
package com.connect;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.IOException;
public class Droidian extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
PackageManager i = getApplicationContext().getPackageManager();
i.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
if (isMyServiceRunning() == false) {
startService(new Intent(getApplicationContext(), DroidianService.class));
Log.i("com.connect", "startService");
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (DroidianService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
After executing MainActivity.java , Droidian.java should run as this is the class which would be doing all the function. I don't know how to call the other class in MainActivity.java class. Here is my Manifest file snippet.
Android Manifest.xml
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.connect"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<supports-screens android:resizeable="true"
android:largeScreens="true"
android:xlargeScreens="true"
/>
<application
android:allowBackup="false"
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:persistent="true">
<activity
android:name="com.connect.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.connect.SampleDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/device_admin" />
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
</intent-filter>
</receiver>
<activity
android:name="com.connect.Droidian"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You cant declare two activities as LAUNCHER. change your droidian activity as DEFAULT.
<activity
android:name="com.connect.Droidian"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Add this to your onCreate
Intent intent = new Intent(getApplicationContext(), Droidian.class);
startActivity(intent);
A few issues:
At first, there is the launcher thing Yogesh mentioned. The launcher category in the intent filter means, that this Activity is the one that gets called first, thus there can only exist one launcher.
It isn't exactly clear if you really want Droidian to be a Activity, since you plainly call it a class. Is it meant to have its own view, or should it be a worker class? If the later, don't extend Activity, just make it a regular class. You then can call the functions by instanciating it in your MainActivity like Droidian mDroidian = new Droidian() or making your functions static.
If you really intent to use a Activity and 'call onCreate', you have to start the Activity. Certain methods can't be started manually but are called automatically once you start an Activity, see the Android reference on Activities, especially the 'Activity Lifecycle' section.
The easiest way to start an Activity would be
Intent intent = new Intent(MainActivity.this, Droidian.class);
startActivity(intent);
Also you might want to have a look at the Android Developer trainings, especially the one about starting an activity.

how to mopub ads add in application

i want to add ads banner in my application i have integrate mopub sdk with my project and import and add library to the my project now my question is how to add banner disply and where code i have to write in my application java code and xml code about ads so please help enyone
my java code and mainifest file code is given below
mainactivity.java
package com.example.ration;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView web;
int k;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web=(WebView)findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
web.setWebViewClient(new WebViewClient());
web.getSettings().setBuiltInZoomControls(true);
web.loadUrl("http://dcs-dof.gujarat.gov.in/live-info.htm");
// web.getProgress();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,1,menu.NONE,"About");
menu.add(0,2,menu.NONE,"Feedback");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id == 1)
{
Toast.makeText(MainActivity.this,"About",Toast.LENGTH_LONG).show();
Intent i=new Intent(MainActivity.this,about.class);
startActivity(i);
}
else {
Toast.makeText(MainActivity.this,"Feedback",Toast.LENGTH_LONG).show();
Intent i2 =new Intent(MainActivity.this,feedback.class);
startActivity(i2);
}
return super.onOptionsItemSelected(item);
}
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this,"Press Again to Exit", Toast.LENGTH_SHORT).show();
}
}
and my manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ration"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ration.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.ration.about"></activity>
<activity android:name="com.example.ration.feedback"></activity>
<activity android:name="com.mopub.mobileads.MoPubActivity" android:configChanges="keyboardHidden|orientation"/>
<activity android:name="com.mopub.mobileads.MraidActivity" android:configChanges="keyboardHidden|orientation"/>
<activity android:name="com.mopub.mobileads.MraidBrowser" android:configChanges="keyboardHidden|orientation"/>
<activity android:name="com.mopub.mobileads.MraidVideoPlayerActivity" android:configChanges="keyboardHidden|orientation"/>
<activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
<activity android:name="com.millennialmedia.android.MMActivity" android:theme="#android:style/Theme.Translucent.NoTitleBar" android:configChanges="keyboardHidden|orientation|keyboard" />
<activity android:name="com.millennialmedia.android.VideoPlayer" android:configChanges="keyboardHidden|orientation|keyboard" />
</application>
</manifest>
I think you should better go through the guide for Mopub Banner Ads Integration which explains you the steps of banner ads integration.
Hope this will help you.
Use view in XML file
<com.mopub.mobileads.MoPubView
android:id="#+id/mrect_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_weight="1" />
in activity Load code
pass id of view in below function ,unit id of ur app,and keywords of cataogry of ads
public void loadMoPubView(MoPubView moPubView, String adUnitId, String keywords) {
if (moPubView == null) {
Utils.logToast(LockScreenActivity.this, "Unable to inflate MoPubView from xml.");
//Toast.makeText(this, "Unable to inflate MoPubView from xml.", Toast.LENGTH_SHORT).show();
return;
}
try {
Utils.validateAdUnitId(adUnitId);
} catch (IllegalArgumentException exception) {
Utils.logToast(LockScreenActivity.this, exception.getMessage());
return;
}
moPubView.setBannerAdListener(this);
moPubView.setAdUnitId(adUnitId);
moPubView.setKeywords(keywords);
moPubView.setAutorefreshEnabled(true);
moPubView.loadAd();
}

onCreate method not called in android

I have created 2 activities.When i call second activity from first via intent then onCreate method of second activity does not called.Although first activity's onCreate method is called normally as it should be.
Below is the code for first activity.
package com.webesperto.webespertofirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int counter;
Button add, sub;
TextView tView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
tView = (TextView) findViewById(R.id.textView1);
// Intent in = new Intent(AC);
add.setOnClickListener(this);
sub.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bAdd:
tView.setText(++counter + "");
try {
Intent nextIntentView = new Intent(MainActivity.this, ShowValueActivity.class);
nextIntentView.putExtra("key", "counter");
startActivity(nextIntentView);
}
catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.bSub:
tView.setText(--counter + "");
break;
default:
break;
}
}
}
Code for second activity.
package com.webesperto.webespertofirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class ShowValue extends Activity {
TextView tv_showValue1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_value);
tv_showValue1 = (TextView) findViewById(R.id.tv_showValue);
Intent gotIntent = (Intent) this.getIntent();
Bundle gotBundle = gotIntent.getExtras();
tv_showValue1.setText(gotBundle.getString("key"));
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webesperto.webespertofirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.webesperto.webespertofirstapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShowValueActivity"
android:label="#string/title_activity_show_value" >
</activity>
</application>
</manifest>
you have
<activity
android:name=".ShowValueActivity"
android:label="#string/title_activity_show_value" >
</activity>
instead of
<activity
android:name=".ShowValue"
android:label="#string/title_activity_show_value" >
</activity>
Since your code reads
public class ShowValue extends Activity {
Though, why doesnt your application crash saying NoActivityFoundException ??
please have a look on manifest
change
<activity
android:name=".ShowValueActivity"
android:label="#string/title_activity_show_value" >
</activity>
to
<activity
android:name=".ShowValue"
android:label="#string/title_activity_show_value" >
</activity>
yours manifest should be like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webesperto.webespertofirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.webesperto.webespertofirstapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShowValue"
android:label="#string/title_activity_show_value" >
</activity>
</application>
</manifest>
Change your Second Activity name in class file like this:
package com.webesperto.webespertofirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class ShowValueActivity extends Activity {
TextView tv_showValue1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_value);
tv_showValue1 = (TextView) findViewById(R.id.tv_showValue);
Intent gotIntent = (Intent) this.getIntent();
Bundle gotBundle = gotIntent.getExtras();
tv_showValue1.setText(gotBundle.getString("key"));
}
}
It will work:)

Android:Broadcast demo not working

I am new to android, i am trying a broadcast demo, I gave my best effort by reading the documentation but its not working. Please have a look at my code:
BroadcastDemoActivity.java
package com.broadcastdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class BroadcastDemoActivity extends Activity {
/** Called when the activity is first created. */
public static final String PUBLIC_HOLIDAYS = "com.paad.action.PUBLIC_HOLIDAYS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
}
}
Receive.java
package com.broadcastdemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String message = intent.getStringExtra("Holiday");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcastdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".BroadcastDemoActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Receive">
<intent-filter>
<action android:name="com.paad.action.PUBLIC_HOLIDAYS"/>
</intent-filter>
</receiver>
</application>
</manifest>
I know that i am missing something which i am not aware of, please help.
I believe your problem is in the call to sendBroadcast.
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(getIntent());
You are not sending the intent that you construct, you're sending the intent returned from getIntent(), which will be the intent that the activity was started with.
It should be
Intent intent = new Intent(PUBLIC_HOLIDAYS);
intent.putExtra("Holiday", "8th April is a holiday");
sendBroadcast(intent);

Starting Activity from a non-Activity in c2dm not showing

I am trying to display messages from C2DM so When I start an Activity from a non activity it works but only first time. My activity contains View and close button so if the user is not inside the app when he receive the push notification then it should start the app when he press view button or close it on close this works as well but when user press view button and enters the app after than I am unable to start the activity again, it seems like the activity is there but its not visible to user. My code is as below , hope you understand what I am saying. The C2DM code example used is taken from here
C2DMReceiver
package com.mks.android.example;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.android.c2dm.C2DMBaseReceiver;
import com.google.android.c2dm.C2DMessaging;
import com.mks.android.example.activity.MessageDialogActivity;
public class C2DMReceiver extends C2DMBaseReceiver {
private static String senderId = "mysenderemail#gmail.com";
String registrationId;
public C2DMReceiver() {
super(senderId);
}
#Override
public void onRegistrered(Context context, String registrationId) {
this.registrationId = registrationId;
Log.e("Error", registrationId);
}
#Override
public void onUnregistered(Context context) {
C2DMessaging.register(context, senderId);
}
#Override
public void onError(Context context, String errorId) {
Log.w("Error", errorId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("Error", "MessageReceived");
Bundle bundle = intent.getExtras();
intent = new Intent();
intent.putExtra("messageBundle", bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setClass(context, MessageDialogActivity.class);
startActivity(intent);
// load message display activity here
}
}
MESSAGE DIALOG ACTIVITY CLASS
package com.mks.android.example.activity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.mks.android.example.R;
import com.mks.android.example.activity.list.Functions;
public class MessageDialogActivity extends Activity {
private Functions func = new Functions();
private int isAppActive = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showMessages();
}
private void showMessages(){
Bundle bundle = getIntent().getBundleExtra("messageBundle");
String title = bundle.getString("title");
String message = bundle.getString("message");
setContentView(R.layout.c2dm_message);
TextView txtTitle = (TextView) findViewById(R.id.title);
TextView txtMessage = (TextView) findViewById(R.id.message);
Button btnView = (Button) findViewById(R.id.btnView);
Button btnClose = (Button) findViewById(R.id.btnClose);
txtTitle.setText(title);
txtMessage.setText(message);
this.isAppActive = func.getAppState(this);
if(isAppActive==1){
btnView.setVisibility(View.GONE);
}
btnView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isAppActive == 0){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.mks.android.example","com.mks.android.example.activity.MainActivity"));
startActivity(intent);
}
MessageDialogActivity.this.finish();
}
});
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
showMessages();
}
}
AndroidManifest FIle
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mks.android.example"
android:versionCode="1"
android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="4" />
<application android:label="#string/app_name" android:icon="#drawable/icon_launcher" android:debuggable="true">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".activity.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.MessageDialogActivity" android:theme="#style/DialogNoTitle" android:activity android:launchMode="singleTop" />
<service android:name=".C2DMReceiver" />
<!-- Only C2DM servers can send messages for the app. If permission is not set - any other app can generate it -->
<receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiver" 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="com.mks.android.example" />
</intent-filter>
<!-- Receive the registration id -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.mks.android.example" />
</intent-filter>
</receiver>
</application>
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
<permission android:name="com.mks.android.example.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.mks.android.example.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive message -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
If i remove androidLaunchMode singleTop form manifest file and add set flag to multipleTask in C2DMReciver class it works but i get lots of dialog for each message. Thanks for help .
Set flag to singletop , the code to call messagedialogactivity is as under:
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setClass(context, MessageDialogActivity.class);

Categories

Resources