Cannot Find MainActivity for Intent Inside Cordova PlugIn - android

I am writing my own cordova plugin for Android. I have the plugin working inside a standalone Android project. I cannot seem to get my activity to start though from the plugin java file. It keeps firing errors that it cannot find MainActivity (cannot find symbol). I am hoping it is an easy fix that I seem to be missing.
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.testplugin" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
Plug-In Java:
package com.myapp.testplugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.provider.Settings;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestPlugin extends CordovaPlugin {
public static final String TAG = "Test Plugin";
/**
* Constructor.
*/
public TestPlugin() {}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* #param cordova The context of the main Activity.
* #param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Log.d(TAG,"Init TestPlugin");
}
#Override
public boolean execute(final String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Context context = cordova.getActivity().getApplicationContext();
Intent intent = new Intent(context, MainActivity.class);
cordova.getActivity().startActivity(intent);
}
});
return true;
}
}
Error is occuring here:
Intent intent = new Intent(context, MainActivity.class);

I solved it this way:
Class mainActivity;
Context context = getApplicationContext();
String packageName = context.getPackageName();
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();
try {
//loading the Main Activity to not import it in the plugin
mainActivity = Class.forName(className);
} catch (Exception e) {
e.printStackTrace();
}
Intent openActivityIntent = new Intent(context, mainActivity);

Related

BroadcastReceiver onReceive doesn't get called on Huawei Device

We have a requirement to show an acknoldgement screen after user share some texts on Messaging apps such as Whatsapp, Telegram, SMS etc..
We have been using the react-native-share library for this and it works fine on non Huawei devices. However, Huawei devices doesn't return success/failure when user share hence the app gives issues on Huawei devices.
Upon checking the react-native-share library internal codes, it seems the BroadcastReceiver onReceive method does not get triggered when user choose and app on HuaweiChooser.
I created the following sample code to simulate this and on Non-Huawei devices this code's onReceive method get triggered but not in Huawei devices.
Appreciate any help regarding this.
This is the Sample code
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button shareButton = findViewById(R.id.button);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooser;
IntentSender intentSender = MyReceiver.getIntentSender(getApplicationContext());
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
chooser = Intent.createChooser(sendIntent,"Sharing Rocks",intentSender);
chooser.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
}else{
chooser = Intent.createChooser(sendIntent,"Sharing Rocks");
}
startActivityForResult(chooser, 1234);
}
});
}
}
Receiver.Java
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private static MyReceiver myReceiver;
private static final String EXTRA_RECEIVER_TOKEN = "receiver_token";
public static IntentSender getIntentSender(Context context){
String intentAction = context.getPackageName()+"_ACTION";
myReceiver = new MyReceiver();
context.registerReceiver(myReceiver, new IntentFilter(intentAction));
Intent intent = new Intent(intentAction);
intent.setPackage(context.getPackageName());
intent.putExtra(EXTRA_RECEIVER_TOKEN,myReceiver.hashCode());
PendingIntent callback = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return callback.getIntentSender();
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("//// Inside onReceive");
ComponentName target = intent.getParcelableExtra(Intent.EXTRA_CHOSEN_COMPONENT);
System.out.println("//// target : " + target);
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lk.infinitx.huaweisharetest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.HuaweiShareTest">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"></receiver>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I change chooser title with "null" and my problem solved.
val chooser = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Intent.createChooser(sendIntent, null, pendingIntent.intentSender)
} else {
Intent.createChooser(sendIntent, null)
}

React native clipboard listener service for android

I am working on an app in react native. I am searching for a code when my app is in the background or has killed. I want a service like notifcationListnerService which invokes the app again. want a similar service that is always running and when a user copies something it will show a push notification to the user like that you have copied something.
Here is what I have tried but these are too complex to understand because these are in java.
Android ClipBoard Manager
Android ClipBoard With Example
This question from StackOverflow also does not have any answer
A solution for GitHub but too complex
one thing I didn't need #react-native-community/clipboard or something like this. the thing that I need is to show push notification on copying something for any app installed of the device.
So Finally searching for two days finally I have implemented what I want. I am showing a toast, not a notification(will implement it later). I am sharing my code but still, I have a problem when my application restart its service for clipboard manager the service is running as I see it in the logcat. Here is my code.
ClipboardMonitorService.java
package com.wm;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Date;
public class ClipboardMonitorService extends Service {
private static final String TAG = "ClipboardManager";
private static final String FILENAME = "clipboard-history.txt";
private File mHistoryFile;
private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
#Override
public void onCreate() {
super.onCreate();
Log.e("service is running","service is running");
// TODO: Show an ongoing notification when this service is running.
mHistoryFile = new File(getExternalFilesDir(null), FILENAME);
mClipboardManager =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
Log.d(TAG, "onPrimaryClipChanged");
ClipData clip = mClipboardManager.getPrimaryClip();
mThreadPool.execute(new WriteHistoryRunnable(clip.getItemAt(0).getText()));
Log.e("Copied Text","hahah"+clip.getItemAt(0).getText());
Toast.makeText(getApplicationContext(),"My App toast",Toast.LENGTH_SHORT).show();
}
};
private class WriteHistoryRunnable implements Runnable {
private final Date mNow;
private final CharSequence mTextToWrite;
public WriteHistoryRunnable(CharSequence text) {
mNow = new Date(System.currentTimeMillis());
mTextToWrite = text;
}
#Override
public void run() {
if (TextUtils.isEmpty(mTextToWrite)) {
// Don't write empty text to the file
return;
}
if (isExternalStorageWritable()) {
try {
Log.i(TAG, "Writing new clip to history:");
Log.i(TAG, mTextToWrite.toString());
BufferedWriter writer =
new BufferedWriter(new FileWriter(mHistoryFile, true));
writer.write(String.format("[%s]: ", mNow.toString()));
writer.write(mTextToWrite.toString());
writer.newLine();
writer.close();
} catch (IOException e) {
Log.w(TAG, String.format("Failed to open file %s for writing!",
mHistoryFile.getAbsoluteFile()));
}
} else {
Log.w(TAG, "External storage is not writable!");
}
}
}
}
This is used for when the app is closed or the device is restarted then it will start the service again.
BootUpRecever.java
package com.wm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class BootUpReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == Intent.ACTION_BOOT_COMPLETED){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//log("Starting the service in >=26 Mode from a BroadcastReceiver")
context.startForegroundService(new Intent(context, ClipboardMonitorService.class));
return;
}
//log("Starting the service in < 26 Mode from a BroadcastReceiver")
context.startService(new Intent(context, ClipboardMonitorService.class));
}
}
}
to start the activity as the app start
MainActivity.java
package com.wm;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
#Override
protected String getMainComponentName() {
return "wm";
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// TODO: Show the contents of the clipboard history.
startService(new Intent(this, ClipboardMonitorService.class));
}
}
Here are the permissions and to start the service
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wm">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
<service
android:name=".ClipboardMonitorService"
android:label="Clipboard Monitor"
android:exported="false"/>
<receiver
android:name=".BootUpReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>

My App keeps taking me back to signup page even after it checks if the user is logged in

I have added the splash screen to launch every time the app starts or even gets killed , then splash screen checks for the user if is logged in but unfortunately it directs me to the mainactivity but then later if takes me back to signup page after some couple of seconds and am not getting any error what am i missing here fellaz thanks alot
Hereis my Manifest
```
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.univibezstudios.ocappservice.ocapp.signuppage"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.LoginScreen" />
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivity" />
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivityCenterofInformation"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivityAEA"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivitySNAL"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivityBvm"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivityForest"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivitySocial"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.MainActivityCollegeofAgriculture"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.IntroActivity"/>
<activity android:name="com.univibezstudios.ocappservice.ocapp.WelcomeScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>```
Here is my welcomescreen as the splash screen
```package com.univibezstudios.ocappservice.ocapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.data.model.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.univibezstudios.ocappservice.ocapp.WelcomeScreen;
public class WelcomeScreen extends AppCompatActivity {
private ImageView logo;
private static int SPLASH_TIME_OUT = 5000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFullscreen ();
setContentView (R.layout.welcomescreen);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance ();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser ();
if(firebaseUser != null)
{
startActivity (new Intent (WelcomeScreen.this
, MainActivity.class));
}
logo= findViewById (R.id.logoocaap);
Animation animation = AnimationUtils.loadAnimation (this,R.anim.splashscreen);
logo.startAnimation (animation);
new Handler ().postDelayed (new Runnable () {
#Override
public void run() {
Intent intent = new Intent (WelcomeScreen.this,IntroActivity.class);
startActivity (intent);
finish ();
}
},SPLASH_TIME_OUT);
}
private void setFullscreen(){
requestWindowFeature (Window.FEATURE_NO_TITLE);
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}```
Your Handler is still running after going to MainActivity and it triggers Introactivity. .There are many ways to do it but my suggestion would be to add your Firebase's user checking condition in Handler.
Remove the firebase's user check from above and put it in Handler's run method.
new Handler ().postDelayed (new Runnable () {
#Override
public void run() {
if(firebaseUser != null) {
startActivity (new Intent (WelcomeScreen.this
, MainActivity.class));
finish ();
} else {
Intent intent = new Intent (WelcomeScreen.this,IntroActivity.class);
startActivity (intent);
finish ();
}
}
},SPLASH_TIME_OUT);
Add below code in else condition of firebase user != Null
new Handler ().postDelayed (new Runnable () { #Override public void run() { Intent intent = new Intent (WelcomeScreen.this,IntroActivity.class); startActivity (intent); finish (); } },SPLASH_TIME_OUT)

activity does not open on event detection

I am following this answer to implement app un-install detector. I am basically trying to open Main Activity when un-installation event is detected, but when I un-istall my app nothing happens (Main Activity does not open before un-install).
Please help, what is wrong with my code?
MainAcivity:
package com.example.appdeveloper.unistalltest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Broadcast Receiver:
package com.example.appdeveloper.unistalltest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class UninstallIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// fetching package names from extras
String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");
if(packageNames!=null){
for(String packageName: packageNames){
if(packageName!=null && packageName.equals("com.example.appdeveloper.unistalltest")){
// User has selected our application under the Manage Apps settings
// now initiating background thread to watch for activity
new ListenActivities(context).start();
}
}
}
else {
Toast.makeText(context, "No package found in Broadcast Receiver", Toast.LENGTH_LONG).show();
}
}
}
ListenActivities.java:
package com.example.appdeveloper.unistalltest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class ListenActivities extends Thread {
boolean exit = false;
ActivityManager am = null;
Context context = null;
public ListenActivities(Context con){
context = con;
am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
public void run(){
Looper.prepare();
while(!exit){
// get the info from the currently running task
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(MAX_PRIORITY);
String activityName = taskInfo.get(0).topActivity.getClassName();
Log.d("topActivity", "CURRENT Activity ::"
+ activityName);
if (activityName.equals("com.android.packageinstaller.UninstallerActivity")) {
// User has clicked on the Uninstall button under the Manage Apps settings
//do whatever pre-uninstallation task you want to perform here
// show dialogue or start another activity or database operations etc..etc..
context.startActivity(new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
exit = true;
Toast.makeText(context, "Done with preuninstallation tasks... Exiting Now", Toast.LENGTH_LONG).show();
}
else if(activityName.equals("com.android.settings.ManageApplications")) {
// back button was pressed and the user has been taken back to Manage Applications window
// we should close the activity monitoring now
exit=true;
}
}
Looper.loop();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.appdeveloper.unistalltest">
<uses-permission android:name="android.permission.GET_TASKS"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".UninstallIntentReceiver">
<intent-filter android:priority="0">
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
</application>
</manifest>
Your app can't know when the user uninstall it since Android 4.0+. I had a similar problem, but didn't found a way to do it. The only things I found today (i already gave up with my app, but maybe it can help you) is this: https://developer.android.com/guide/topics/admin/device-admin.html
I'm not sure this will help you, but it is the only thing i found.

Unknown reason why app throws an error

I have an app that before worked fine but recently won't run.
Before it only had offline features, the most complex would be the local notification - but I need to add a GCM functionality to it. I searched for answers but it's so difficult to understand.
I tried to copy the code of a tutorial I've seen. I learned that I need a thing called GCMRegistrar but I don't know where to get it. Then I tested my app, there were errors of course because I don't have the gcmregistrar.
What I did is I enclosed the code in a comment block and ran the app again. That's when my app won't run anymore. After a few days of this mishap, I decided to create another app where I would put all the offline feature of my app. after that copying and pasting, I tried to run my the new app but it also won't run.
I've searched for ways to fix it and found a few fixes. Those fix works for other apps but won't work for my new app.
Here's my MainActivity.java, this one has the local notification
package com.example.mypower_build101;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button addDevice, showDevice, showDialog;
String[] arrContentTxt;
final Context ctx = this;
int notifCount;
int x = 0;
Handler notifLauncher, notifStopper;
String contentTxt;
Resources res = getResources();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addDevice = (Button)findViewById(R.id.btnAddDevice);
showDevice = (Button)findViewById(R.id.btnShowDevice);
showDialog = (Button)findViewById(R.id.btnShowDialog);
arrContentTxt = res.getStringArray(R.array.notifContentText);
//contentTxt = arrContentTxt[1];
showDialog.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
/*DialogFragment diag = new SwitchCheckChange();
diag.show(getFragmentManager(), "cbo Click");*/
showNotif();
}
});
useNotifLauncher();
useNotifStopper();
}
public void useNotifLauncher(){
notifLauncher = new Handler();
notifLauncher.postDelayed(runNotif, 50000);
}
public Runnable runNotif = new Runnable(){
#Override
public void run() {
showNotif();
notifLauncher.postDelayed(runNotif, 50000);
}
};
public void useNotifStopper(){
notifStopper = new Handler();
notifStopper.postDelayed(stopNotif, 40000);
}
public Runnable stopNotif = new Runnable(){
#Override
public void run() {
cancelNotification(x);
notifStopper.postDelayed(stopNotif, 40000);
}
};
public void addClick(View v){
Intent i = new Intent(this, AddDeviceForm.class);
startActivity(i);
}
public void showClick(View v){
Toast.makeText(getBaseContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent i = new Intent(this, ListViewForm.class);
startActivity(i);
}
public void showNotif(){
Uri notifSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent i = new Intent(MainActivity.this, NotifReceiver.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, i, 0);
//String[] notifTitle = R.array.notifTitle;
Notification notif = new Notification.Builder(this)
.setContentTitle("MyPower Reminder")
.setContentText("Unplug unused appliances and chargers")
//.setContentText(contentTxt)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pi)
.setSound(notifSound)
.addAction(0, "View Full Reminder", pi)
.build();
NotificationManager notifMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notifMgr.notify(0, notif);
}
public void cancelNotification(int notificationId){
if (Context.NOTIFICATION_SERVICE!=null) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
nMgr.cancel(notificationId);
}
}
}
here's my androidmanifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mypower_build101"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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=".AddDeviceForm"
android:label="#string/title_activity_add_device_form" >
</activity>
<activity
android:name=".ListViewForm"
android:label="#string/title_activity_list_view_form" >
</activity>
<activity
android:name=".NotifReceiver"
android:label="#string/title_activity_notif_receiver" >
</activity>
</application>
</manifest>
I'm not putting everything here because it would be to lengthy and I think the problems might be at the MainActivity or the android manifest.
If you could teach me how use the gcm thing that would be very, very, much appreciated.
Hi guys for some reason my post have an error so please use and look at this document. here's the document link
https://www.dropbox.com/s/tc2j2a2pan53r96/Ricky%20Manalo%20LogCat%20Log.docx?dl=0

Categories

Resources