How to receive ACTION_SCREEN_OFF with a "always running" service - java

I want to create an app that set/reset a timer to reproduce a song if the mobile spend 8 hours with the screen off.
I want to create a service that receive ACTION_SCREEN_OFF, but the problem is that when the app is killed from recent apps, the service is killed. I try with START_STICKY but the service is not restarted (onCreate is called sometimes but not onStart Command). I try to set in Manifest but the receiver must be register.
By now I only want that receiver detect ACTION_SCREEN_OFF.
I Have this code:
MainScreen.java (MainActivity)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainScreen extends Activity implements View.OnClickListener{
public static final String MSG_TAG = "NoSleepMore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
findViewById(R.id.start_service_button).setOnClickListener(this);
findViewById(R.id.stop_service_button).setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(), LockService.class);
switch (v.getId()) {
case R.id.start_service_button:
Log.e(MSG_TAG,"Service started");
//starts service for the given Intent
startService(intent);
break;
case R.id.stop_service_button:
Log.e(MSG_TAG,"Service stopped");
//stops service for the given Intent
stopService(intent);
break;
}
}
}
LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class LockService extends Service {
#Override
public IBinder onBind(Intent arg0) {
Log.i(MainScreen.MSG_TAG, "onBind()" );
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(MainScreen.MSG_TAG, "Service Created");
/* Filtrar Acciones Capturadas */
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
// Listener
final BroadcastReceiver mReceiver = new ScreenReceiver();
// Registar Listener
registerReceiver(mReceiver, filter);
return Service.START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
Log.i(MainScreen.MSG_TAG, "onCreate()");
}
#Override
public void onDestroy() {
Log.i(MainScreen.MSG_TAG, "onDestroy()");
}
}
ScreenRecive.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.i(MainScreen.MSG_TAG,"OnReceive->");
// Log Handel
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action ON");
}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e(MainScreen.MSG_TAG,"Action UserPresent");
}
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.mangel.nosleepmore">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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=".MainScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</receiver>
<service android:name=".LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>
</manifest>
The Main activity is just two buttons.
BTW I just need that run over Android 8.0.

Related

How to start activity or service (Either) on bootup completed?

I'm trying to find out how to run a service (Any service, may be foreground or background) when device boots. I've tried implementing broadcast receiver but it seems not to work.
Below is my full code.
1.AndroidManifext.xml - I made sure I included the service and broadcast receiver here. Are there any permissions I may be lacking?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testboot">
<!-- Example need below permission. -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name="com.example.testboot.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.example.testboot.BootDeviceReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.example.testboot.RunAfterBootService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
2.MainActivity.java - This is the launch class, I made it call the broadcast receiver class. Asides from that, it doesn't have anything else.
package com.example.testboot;
import android.content.Intent;
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);
Intent intent = new Intent("com.example.testboot.BootDeviceReceiver");
sendBroadcast(intent);
}
}
3.BootDeviceReceiver.java -This is the class responsible for knowing when device has booted up (Extends Broadcast receiver)
package com.example.testboot;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class BootDeviceReceiver extends BroadcastReceiver {
private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message = "BootDeviceReceiver onReceive, action is " + action;
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);
if(Intent.ACTION_BOOT_COMPLETED.equals(action))
{
//startServiceDirectly(context);
startServiceByAlarm(context);
}
}
/* Start RunAfterBootService service directly and invoke the service every 10 seconds. */
private void startServiceDirectly(Context context)
{
try {
while (true) {
String message = "BootDeviceReceiver onReceive start service directly.";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// This intent is used to start background service. The same service will be invoked for each invoke in the loop.
Intent startServiceIntent = new Intent(context, RunAfterBootService.class);
context.startService(startServiceIntent);
// Current thread will sleep one second.
Thread.sleep(10000);
}
}catch(InterruptedException ex)
{
Log.e(TAG_BOOT_BROADCAST_RECEIVER, ex.getMessage(), ex);
}
}
/* Create an repeat Alarm that will invoke the background service for each execution time.
* The interval time can be specified by your self. */
private void startServiceByAlarm(Context context)
{
// Get alarm manager.
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Create intent to invoke the background service.
Intent intent = new Intent(context, RunAfterBootService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
long intervalTime = 60*1000;
String message = "Start service use repeat alarm. ";
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);
// Create repeat alarm.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}
}
3.RunAfterBootService.java - This is the service class, should be displayed after device completes booting up.
package com.example.testboot;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
public class RunAfterBootService extends Service {
private static final String TAG_BOOT_EXECUTE_SERVICE = "BOOT_BROADCAST_SERVICE";
public RunAfterBootService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onCreate() method.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String message = "RunAfterBootService onStartCommand() method.";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onStartCommand() method.");
Intent i = new Intent();
i.setClass(RunAfterBootService.this,MainActivity.class);
startActivity(i);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
So far, when I restart my device nothing happens at all.
Has your app an icon ? you must open your app one time then you can receive the boot_complete broadcast.

avoid of send null from destroyed activity to restarted service

I want to programing app for data track in background , so I use service .
I want to write a program that monitors all data sent and received by the device, and when the total volume of received or received messages reaches a specified value, the Internet device is turned off.
So I used the following code to monitor the data:
 
mStartRX = TrafficStats.getTotalRxBytes ();
mStartTX = TrafficStats.getTotalTxBytes ();
And I used the services to work on the background in the background.
To specify the download or upload limit from the user with edittext, I requested this limit in mainactivity and send this value to the service.
The problem is when: When I destroy the program, I will restart the service and get the NULL value and the program crashes.
My application code:
Main Activity :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static Handler mHandler = new Handler();
public static long UPP;
public static long DLL;
Button startService,stopService;
public Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FirstService.mStartRX == TrafficStats.UNSUPPORTED || FirstService.mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText UP = (EditText) findViewById(R.id.UP);
String UPPP = UP.getText().toString();
UPP=Long.parseLong(UPPP);
EditText DL = (EditText) findViewById(R.id.DL);
String DLLL = DL.getText().toString();
DLL=Long.parseLong(DLLL);
Intent intent = new Intent(getApplicationContext(), FirstService.class);
String myString = DLLL;
intent.putExtra("StringName", myString);
startService(intent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(),FirstService.class));
}
});
}
public final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
RX.setText(Long.toString(FirstService.rxBytes));
TX.setText(Long.toString(FirstService.txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Service :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
public class FirstService extends Service{
public static long mStartRX ;
public static long mStartTX ;
public static long rxBytes ;
public static long txBytes ;
public long dl=MainActivity.DLL;
Context context=this;
private final Runnable mRunnable = new Runnable() {
public void run() {
rxBytes = (TrafficStats.getTotalRxBytes()- mStartRX)/1048576;
txBytes = (TrafficStats.getTotalTxBytes()- mStartTX)/1048576;
if (rxBytes==2) {
stopService(new Intent(getBaseContext(),FirstService.class));
Intent i = new Intent(context,MainActivity.class);
context.startActivity(i);
// WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// wifiManager.setWifiEnabled(false);
//معرفی توست برای نمایش یک پیام کوتاه به کاربر در هنگام خاموش کردن وای فای
Toast.makeText(FirstService.this, "هشدار", Toast.LENGTH_LONG).show();
}
mHandler.postDelayed(mRunnable, 1000);
}
};
private Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"staart",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
mHandler.postDelayed(mRunnable, 1000);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
TrafficStats.clearThreadStatsTag();
Toast.makeText(this,"FirstService Stoped",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
super.onDestroy();
}
}
AndroidManifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.alexandre9009.service">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService"
>
</service>
</application>
</manifest>
please help me ...
The problem is with this line
public long dl=MainActivity.DLL;
You're referring to a variable in the Activity, surly when the Activity is destroyed, this variable is no longer in scope, thus you get Null Exception.
You must get this value using the intent.
The other problem is that you can't prevent any service from being killed by the system except foreground services which need to show a notification to the user. But this is not suitable for your situation.
Therefore, the best approach for you is to check whether intent is null or not. If it is not null, you get the value and save it into Preferences or Database or somewhere, if it is null, you retrieve the value from where you stored it before.

Android: Why doesn't my Service start?

I want to learn how to use services in my application, but Service doesn't work! Here is my code.
This is the sample code i have written for the services. Suggest me if i am missing anything.Thanks in Advance
package com.example.utente.test;
import android.content.Intent
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
final String[] numeri =
{"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"
,"1","2","1","2",
"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2",
"1","2","1","2"};
long inizio;
long fine;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizio = System.currentTimeMillis();
Intent i= new Intent(getApplicationContext(), MyService.class);
startService(i);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.riga, numeri);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onResume()
{
super.onResume();
inizio = System.currentTimeMillis();
// new MyService(inizio);
}
#Override
public void onItemClick(AdapterView<?> adattatore, final View componente,
int posizione, long id )
{
Toast.makeText(getApplicationContext(), numeri[posizione],
Toast.LENGTH_LONG).show();
}
}
package com.example.utente.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
long inizio;
long fine;
long tempo;
boolean ciclo=true;
int prova=0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// This is where you would place your code that you want in the
background
// Putting your while loop here will make sure it runs when the app is closed
Toast.makeText(getApplicationContext() ,"COMMAND",
Toast.LENGTH_LONG).show();
while(ciclo)
{
fine = System.currentTimeMillis();
tempo = (fine-inizio)/1000;
if(tempo>10 && prova==0)
{
prova++;
Toast.makeText(getApplicationContext(), "10s",
Toast.LENGTH_LONG).show();
}
}
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
<?xml version="1.0" encoding="utf-8"?>
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.utente.test">
<service
android:name="MyService" />
<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>
</application>
</manifest>
Add your Service to your Manifest as followed:
<service android:name=".MyService" />

How to start service in dialer (default or stock dialer) of android

I want start a service when my dialer (default or stock dialer) open. My service just toasts a message. How to start the service for dialer. The startService command is working in MainActivity, but it is not working while a dialer is open.
My code is shown below:
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chatheads">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DIAL_ACTION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<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>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
MainActivity.java
package com.example.chatheads;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.DialerKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startService,stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
if(getIntent().getAction().equals(Intent.ACTION_DIAL)) {
Intent intent = new Intent(getBaseContext(), MyService.class);
startService(intent);
}
startService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplication(), MyService.class));
}
});
stopService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplication(), MyService.class));
}
});
}
}
Myservice.java
package com..service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
intent.getStringExtra("MY_MESSAGE");
//stopSelf();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
This code is not working. The service starting when the startService calling in MainActivity. But when a dialer open it not working.
I think maybe you can try changing getApplication () to MainActivity.this.
And I think you need to jump from the dialer to MainActivity to get the service started

Where am I wrong with broadcasting info from Java and receiving in Unity?

So I just started working on this project and part of it is sending packages of information from an app in Java to another Unity app.
I have been trying to follow this tutorial but I have problems getting it to work and even somewhat understanding it a bit since I have not worked with Java before.
Here is the current code I have so far.
Main Activity Class
package com.example.service3;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
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;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
startService(new Intent(this, MyService.class));
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Sender class
package com.example.service3;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service
{
private final Handler handler = new Handler();
private int numIntent;
// It's the code we want our Handler to execute to send data
private Runnable sendData = new Runnable() {
// the specific method which will be executed by the handler
public void run() {
numIntent++;
// sendIntent is the object that will be broadcast outside our app
Intent sendIntent = new Intent();
// We add flags for example to work from background
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES );
// SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen.
// By convention, it's suggested to use the current package name
sendIntent.setAction("com.example.service3");
// Here we fill the Intent with our data, here just a string with an incremented number in it.
sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent);
// And here it goes ! our message is send to any other app that want to listen to it.
sendBroadcast(sendIntent);
// In our case we run this method each second with postDelayed
handler.removeCallbacks(this);
handler.postDelayed(this, 1000);
}
};
#Override
public void onStart(Intent intent, int startid) {
numIntent = 0;
// We first start the Handler
handler.removeCallbacks(sendData);
handler.postDelayed(sendData, 1000);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
XML for Sender
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.service3.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>
<service android:enabled="true" android:name="com.example.service3.MyService" />
</application>
Receiver Class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Receiver extends BroadcastReceiver
{
private static Receiver instance;
public static String text ="1";
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
String sentIntent = intent.getStringExtra(Intent.EXTRA_TEXT);
text = "-1";
}
public static void createInstance()
{
if(instance == null)
{
instance = new Receiver();
}
}
}
Unity Android Manifest
<application android:theme="#android:style/Theme.NoTitleBar.Fullscreen" android:icon="#drawable/app_icon" android:label="#string/app_name" android:debuggable="false" android:isGame="true" android:banner="#drawable/app_banner">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="#string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<receiver android:name="com.example.receiver3.MyReceiver" >
<intent-filter>
<action android:name="com.example.receiver3" ></action>
</intent-filter>
</receiver>
</application>
I realise this is a massively large post but I simply do not know what to do at this point and am somewhat considering backing out of the project for the fact that I have no idea how to get Java to communicate with Unity.
Thanks in advance.

Categories